สร้าง Cookie (Create)
วิธีง่ายที่สุด กำหนดค่าสตริงให้ document.cookie
document.cookie = "key1=value1;key2=value2;expires=date";
Attribute expires เป็นทางเลือก
ตัวอย่าง
<html>
<head>
<script>
function WriteCookie() {
if( document.myform.customer.value == "" ) {
alert("Enter some value!");
return;
}
cookievalue = escape(document.myform.customer.value) + ";";
document.cookie = "name=" + cookievalue;
document.write("Setting Cookies : " + "name=" + cookievalue );
}
</script>
</head>
<body>
<form name="myform" action="">
Enter name: <input type="text" name="customer"/>
<input type="button" value="Set Cookie" onclick="WriteCookie();"/>
</form>
</body>
</html>
อ่าน Cookie (Read)
การอ่าน Cookie ง่ายเท่ากัน เพราะค่า document.cookie คือ Cookie เอง String จะเก็บ Key=Value คั่นด้วย Semicolon
ตัวอย่าง
<html>
<head>
<script>
function ReadCookie() {
var allcookies = document.cookie;
document.write("All Cookies : " + allcookies );
cookiearray = allcookies.split(';');
for(var i=0; i