How do you use the jQuery Cookie plugin to ensure a checked checkbox remains checked when refreshing the page or leaving and returning to the page?
1 Answer
If using the $.cookie jQuery plugin...
var checkbox = $('#your-form :checkbox:first'),
checkboxCookieName = 'checkbox-state';
checkbox.prop('checked', +$.cookie(checkboxCookieName));
checkbox.click(function() {
$.cookie(checkboxCookieName, +this.checked);
});
3 Comments
ShankarSangoli
There is unwanted
+ while setting the checkbox checked prop.alex
@ShankarSangoli How is it unwanted? I want to store
'0' or '1' for ease of converting back from string to something falsy.andriy
Also note that .prop() was added in jQuery 1.6. If you using more older plugin it can be replaced with .attr()