Then, the cookies are split using semicolon (;) and a FOR LOOP is executed over the cookies collection.
Inside the FOR LOOP, cookie object is fetched and name parameter is matched with the name of the cookie. If matched the cookie Name along with the Value are set in the properties of cookie object.
Name:
<input type="text" id="txtName"/>
<br />
<br />
<input id="btnWrite" type="button" value="Write Cookie" onclick="WriteCookie('Name')" />
<input id="btnRead" type="button" value="Read Cookie" onclick="ReadCookie('Name')" />
<input id="btnDelete" type="button" value="Remove Cookie" onclick="DeleteCookie('Name')" />
<script type="text/javascript">
function WriteCookie(name) {
//Define a Cookie object.
var cookieObj = {};
//Set the Cookie Name.
cookieObj.Name = name;
//Set the Cookie Value.
cookieObj.Value = document.getElementById("txtName").value;
//Set Cookie Expiry.
var dt = new Date();
dt.setDate(dt.getDate() + 30);
cookieObj.Expires = dt.toUTCString();
//Save the Cookie in Browser.
document.cookie = cookieObj.Name + "=" + cookieObj.Value + ";=expires=" + dt.toUTCString() + ";path=/";
};
function ReadCookie(name) {
//Define a Cookie object.
var cookieObj = {};
//Reading the Cookie collection.
var cookies = document.cookie.split(';');
//Looping through the Cookie collection.
for (var i = 0; i < cookies.length; i++) {
//Fetch the Cookie object.
var cookie = cookies[i];
//Match the name of the Cookie.
if (cookie.split('=')[0].trim().toLowerCase() == name.toLowerCase()) {
//Set the Cookie Name.
cookieObj.Name = cookie.split('=')[0].trim();
//Set the Cookie Value.
cookieObj.Value = cookie.split('=')[1].trim();
}
}
//Return Cookie value.
alert(cookieObj.Value);
};
function DeleteCookie(name) {
//Set Cookie Expiry to Past date.
var dt = new Date();
dt.setDate(dt.getDate() - 1);
document.cookie = name + "=;expires=" + dt.toUTCString() + ";path=/";
};
</script>