Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(jQuery) Save checkbox state on click in cookie

There are a lot of topics regarding this function, nonetheless I can't seem to get it working. I've googled on this specific case and a bunch of links let me here, but strangly enough I can't seem to get them to work. The only thing I did get working was the following: http://dl.dropbox.com/u/2238080/a/!old/z.htm but as you can see, it doesn't store the state of the box is unchecked.

Regards, Ruben

like image 496
user1913435 Avatar asked Dec 18 '12 16:12

user1913435


2 Answers

You can change ALL your code to just: EDITED to remove part unneeded.

$(document).ready( function(){
   // read the current/previous setting
    $("input.box[type=checkbox]").each(function() {
        var name = $(this).attr('name');
        if ($.cookie(name) && $.cookie(name) == "true") {
            $(this).prop('checked', $.cookie(name));
        }
    });
   // event management
    $("input.box[type=checkbox]").change(function() {
        var name = $(this).attr("name");
        $.cookie(name, $(this).prop('checked'), {
            path: '/',
            expires: 365
        });
    });
});

including getting rid of all these:

$(document).ready( function(){
    remember("[name=1]");
});
...

EDIT: less verbose version:

$("input.box").each(function() {
    var mycookie = $.cookie($(this).attr('name'));
    if (mycookie && mycookie == "true") {
        $(this).prop('checked', mycookie);
    }
});
$("input.box").change(function() {
    $.cookie($(this).attr("name"), $(this).prop('checked'), {
        path: '/',
        expires: 365
    });
});

working example: http://jsfiddle.net/R73vy/

like image 196
Mark Schultheiss Avatar answered Sep 25 '22 13:09

Mark Schultheiss


If you don't strictly need to use cookies, using the newer HTML5 Web Storage (specifically the sessionStorage object in this case) is a lot easier and better than storing in a cookie:

http://www.w3schools.com/html/html5_webstorage.asp

Browser support is pretty full:

http://caniuse.com/#search=sessionstorage

like image 29
Chris Halcrow Avatar answered Sep 25 '22 13:09

Chris Halcrow