Get saved state for collection of flags from local storage after page reload

I have a collection of 20 flags, such as 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 save and delete the state of the checkbox in local storage, which works very well, also the filter function 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 restore the state of each flag after reloading the page. I tried this already with several functions, and my last stand:

$(document).ready(function() {

                      if (localStorage.getItem(this.value) == 'checked'){
                          $(this).attr("checked",true)
                      }

                    })

any help is appreciated.

+5
source share
1 answer

try it

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

$().ready() this , , , $(': checkbox). ( ). , , . .each(). $(': checkbox') (), this

, localStorage , , .

, if (window.localStorage) { /* code here */}


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');
        });
    });
}

, Try jQuery http://try.jquery.com/

+6

All Articles