I am working on a login page for a project and I am wondering how I would go about setting a cookie just to remember the username ?
Advertisement
Answer
Here is the sample code. for html Cookies.
JavaScript
x
59
59
1
<!DOCTYPE html>
2
<html>
3
<head>
4
<script>
5
function getCookie(c_name)
6
{
7
var c_value = document.cookie;
8
var c_start = c_value.indexOf(" " + c_name + "=");
9
if (c_start == -1)
10
{
11
c_start = c_value.indexOf(c_name + "=");
12
}
13
if (c_start == -1)
14
{
15
c_value = null;
16
}
17
else
18
{
19
c_start = c_value.indexOf("=", c_start) + 1;
20
var c_end = c_value.indexOf(";", c_start);
21
if (c_end == -1)
22
{
23
c_end = c_value.length;
24
}
25
c_value = unescape(c_value.substring(c_start,c_end));
26
}
27
return c_value;
28
}
29
30
function setCookie(c_name,value,exdays)
31
{
32
var exdate=new Date();
33
exdate.setDate(exdate.getDate() + exdays);
34
var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
35
document.cookie=c_name + "=" + c_value;
36
}
37
38
function checkCookie()
39
{
40
var username=getCookie("username");
41
if (username!=null && username!="")
42
{
43
alert("Welcome again " + username);
44
}
45
else
46
{
47
username=prompt("Please enter your username:","");
48
if (username!=null && username!="")
49
{
50
setCookie("username",username,365);
51
}
52
}
53
}
54
</script>
55
</head>
56
<body onload="checkCookie()">
57
</body>
58
</html>
59