Originally Posted by
jack.jill
Requirement: In Login Page, there r 2 text fields (for username and pwd) and 1 checkbox.
If we click that checkbox, the username will be stored in cookie. From the second time onwards, when the user logs in, the username field will be prefilled with the value in cookie and checkbox will be checked by default (u can change if u want)
Here is the code for above requirement and it works pretty gooddd:
login.html:
<html>
<head>
<script type="text/javascript" src="D:/cookie.js">
</script>
<script>
function LoginButton(){
window.document.loginForm.action = '<portlet:actionURL></portlet:actionURL>';
window.document.loginForm.submit();
}
</script>
</head>
<body id="bodyId">
<form id="loginForm" name="loginForm" method="post" action="">
UserName <input type="text" name="username"/>
<br><br>
Password <input type="password" name="password"/>
<br><br>
<input type="checkbox" name="name_CheckBox" onclick="javascript:toggle(document);"/>Remember me on this computer
<br><br>
<input name="Login" type="button" onclick="javascript:LoginButton();" value="Login"/>
</form>
<script type="text/javascript">
javascript:checkCookie(document);
</script>
</body>
</html>
cookie.js:
function getCookie(document,NameOfCookie){
if (document.cookie.length > 0){
c_start = document.cookie.indexOf(NameOfCookie + "=");
if (c_start != -1){
c_start = c_start + NameOfCookie.length + 1;
c_end = document.cookie.indexOf(";",c_start);
if (c_end == -1) c_end = document.cookie.length;
return unescape(document.cookie.substring(c_start,c_end)) ;
}
}
return "";
}
function setCookie(document,NameOfCookie,value,expiredays){
if (!getCookie(document,NameOfCookie)) {
var exdate = new Date();
exdate.setDate(exdate.getDate()+expiredays);
document.cookie = NameOfCookie+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString());
}
}
function delCookie(document,NameOfCookie) {
if (getCookie(document,NameOfCookie)) {
document.cookie = NameOfCookie + "=" + ";expires=Thu, 01-Jan-70 00:00:01 GMT";
}
}
function checkCookie(document){
name = getCookie(document,'username');
if (name != null && name != ""){
document.loginForm.username.value = name;
document.loginForm.name_CheckBox.checked = true;
}
}
function toggle(document){
if(document.loginForm.name_CheckBox.checked == true){
var fieldValue = document.loginForm.username.value;
setCookie(document,'username',fieldValue,365);
}else{
delCookie(document,'username');
}
}