- This topic is empty.
Viewing 4 posts - 1 through 4 (of 4 total)
Viewing 4 posts - 1 through 4 (of 4 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Set/Delete Cookie with Checkbox??
I have a checkbox and a
. I would like if checkbox is checked, the
will change and the data will be stored in cookies. I was "WARRGHH!!" with JQuery cookie and totally not understand. Can someone explain how to set cookies properly?
Thank's for your help.
Here's my explosive code. Be careful when touching: http://jsfiddle.net/tovic/z59DP/embedded/result/
Forget about cookies, use local storage :P
Oh, I thought I remembered simpler examples and an example on how to check if localStorage exists. Try this (demo):
$(function() {
// check if localStorage exists, from Modernizr
try {
if (!localStorage.getItem) { return false; }
} catch(e) {}
if (localStorage["preew"]) {
$('pre').addClass('light');
$('input:checkbox').prop('checked', true);
}
$('input:checkbox').change(function() {
if ($(this).is(':checked')) {
localStorage["preew"] = true;
$('pre').addClass('light');
} else {
localStorage["preew"] = false;
$('pre').removeClass('light');
}
});
});
I didn’t want to confuse you, but the checkbox change function can be shortened into this:
$('input:checkbox').change(function() {
var chk = $(this).is(':checked');
localStorage["preew"] = chk;
$('pre')[ chk ? "addClass" : "removeClass" ]('light');
});
YEAHHH!!! xD
$("input#togglePre").change(function() {
if ($(this).is(':checked')) {
$("body").addClass('prelight');
createCookie("pre", "prelight", 1000);
} else {
$("body").removeClass('prelight');
eraseCookie("pre", "prelight");
}
});
if (readCookie("pre")) {
$("body").addClass('prelight');
$('input#togglePre').attr('checked', 'checked');
}