In this article I will explain with an example, how to add Cookie using jQuery i.e. set (save) Cookie in Browser using jQuery.
The jQuery Cookie Plugin
This article makes use of the jQuery Cookie Plugin. This article covers basics of adding and reading Cookies. For more advanced usage, please refer jQuery Cookie Plugin Documentation.
Set (Save) Cookies in jQuery
The following HTML Markup consists of an HTML TextBox and a HTML Button for adding cookie using jQuery.
Inside the jQuery document ready event handler, each button has been assigned with jQuery Click event handler.
Adding Cookies
When the Add Cookie Button is clicked, the respective jQuery event handler is executed which saves the value of the Name TextBox to browser Cookie using the $.cookie function.
The $.cookie function accepts two parameters, first the Name (Key) of the Cookie and second the Value to be stored in the Cookie.
Reading Cookies
When the Read Cookie Button is clicked, the respective jQuery event handler is executed which fetches the value of the Cookie using the $.cookie function.
In order to the read the Cookie value, the $.cookie function is used with one parameter i.e. the Name (Key) of the Cookie.
The value read from the Cookie is displayed using JavaScript Alert Message Box.
Name:
<input type="text" id="txtName" />
<br />
<br />
<input id="btnAdd" type="button" value="Add Cookie" />
<input id="btnRead" type="button" value="Read Cookie" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnAdd").click(function () {
$.cookie("Name", $("#txtName").val());
});
$("#btnRead").click(function () {
alert($.cookie("Name"));
});
});
</script>
Screenshot
Demo
Downloads