I am trying to set a cookie using the value of a select box option. I am using the jquery.cookie.js plugin found at: https://github.com/carhartl/jquery-cookie
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js'></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#set_state").change(function() {
var theState = $(this).val();
$.cookie('set_state', theState, { expires: 5, path: '/' });
});
});
</script>
</head>
<body>
<select id="set_state" name="state">
<option value="" selected="selected"></option>
<option value="">None</option>
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="AZ">AZ</option>
<option value="AR">AR</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<!-- no need to post them all here -->
</select>
</body>
If I use an alert box to show the variable theState
, it works, but I can not get the $.cookie
function to work... what am I doing wrong?
Here the complete example for setting cookies using jQuery cookie plugin.
HTML:
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js'></script>
<script type='text/javascript' src='http://codebins.com/userUploads/3/jquery.cookie.js'></script>
</head>
<body>
<select id="set_state" name="state">
<option value="" selected="selected"></option>
<option value="">None</option>
<option value="AL">AL</option>
<option value="AK">AK</option>
<option value="AZ">AZ</option>
<option value="AR">AR</option>
<option value="CA">CA</option>
<option value="CO">CO</option>
<option value="CT">CT</option>
<!-- no need to post them all here -->
</select>
<input type="button" id="btncookie" value="get cookie" />
<input type="button" id="btndelcookie" value="delete cookie" />
</body>
JQuery:
$(document).ready(function() {
$("#set_state").change(function() {
var theState = $(this).val();
$.cookie('set_state', theState, {
expires: 5,
path: '/'
});
});
$("#btncookie").click(function() {
alert("Your Selected Value from Cookie is : " + $.cookie('set_state'));
});
$("#btndelcookie").click(function() {
$.cookie('set_state', '', {
expires: -1
});
$("#set_state").val("");
alert('Cookie is deleted now, try to get cookie..!');
});
});
Try above example on codebins: http://codebins.com/codes/home/4ldqpc6