retrieve the saved state for a collection of checkboxes from local storage after page reload

checkbox, javascript, jquery, local, storage

Solution

Try this

$(':checkbox').each(function() {
    $(this).prop('checked',localStorage.getItem(this.name) == 'checked');
});

In $(document).ready() function, `this` refers to the document, not to a checkbox, like in the $(':checkbox').click(). Plus if you think about it, you really need a way to iterate through your checkboxes. This is where .each() comes in. Inside the $(':checkbox').each() function, `this` will refer to a specific checkbox

Also it would be a good idea to check that localStorage is actually supported by the browser the code is running on, otherwise you will be getting errors.

a simple way is to wrap everything in an `if (window.localStorage) { /* code here */}`

Improved version

if (window.localStorage) {
    $('.cbcell').on('click',':checkbox',function(){
        var name = this.name;
        var value = this.value;

          if($(this).is(':checked')){
             oTable.fnFilter(name, value,false,true,false,true);
             //shorthand to check that localStorage exists
             localStorage && localStorage.setItem(this.name,'checked');

          } else {
             oTable.fnFilter('',value,false,true,false,true);
             //shorthand to check that localStorage exists
             localStorage && localStorage.removeItem(this.name);
          }
    });


    $(document).ready(function () {
        $(':checkbox').each(function() {
            $(this).prop('checked',localStorage.getItem(this.name) == 'checked');
        });
    });
}

Finally may I suggest spending some time going through the excellent Try jQuery tutorial at http://try.jquery.com/

Problem

i've got a collection of 20 checkboxes like this here: ``` <div class="cbcell"> <input type="checkbox" class="checkbox" id="home_swimming_pool" name="Basen" value="35"> Basen </div> <div class="cbcell"> <input type="checkbox" class="checkbox" id="home_sauna" name="Sauna" value="45"> Sauna </div> ``` with the following code i am saving and removing the checkbox state in the local storage which works very fine, also the filter function of dataTables works fine. ``` <script type="text/javascript" > $(':checkbox').click(function(){ var name = $(this).attr('name'); var value = $(this).val(); if($(this).is(':checked')){ console.log( name, value ); // <- debug oTable.fnFilter(name, value,false,true,false,true); localStorage.setItem(this.name,'checked'); } else { console.log( name, value ); // <- debug oTable.fnFilter('',value,false,true,false,true); localStorage.removeItem(this.name); } //}) }); </script> ``` Please tell me how to retrieve the state of each checkbox after a page reload. I tried it already with several functions and my last stand is: ``` $(document).ready(function() { if (localStorage.getItem(this.value) == 'checked'){ $(this).attr("checked",true) } }) ``` any help is highly appreciated.

Original source