mardi 18 décembre 2018

Checkbox Enable/Disable DIV - Localstorage - Onload load the status

I use this checkbox type in my index.html :

<input class="check-1" type="checkbox" value="1" id="check-1"/>

This code in my .js

$(".Categorie.1").show();
$(".check-1").click(function() {
    if($(this).is(":checked")) {
        $(".Categorie.1").hide();
    } else {
        $(".Categorie.1").show();
    }
});

//localstorage
$('input[type="checkbox"]').each(function(){
    $(this).prop('checked', (localStorage.getItem($(this).attr('id')) === 'true') ? 'checked' : '')
});

$('input[type="checkbox"]')  
  .on('change', function() {
    localStorage.setItem($(this).attr('id'), this.checked);
    if (this.checked) {
      $('.' + $(this).data('target')).show();
    } else {
      $('.' + $(this).data('target')).hide();
    }
  })
  .trigger('change');

When i load the page, no problem, the checkboxes that are checked are still ticked. But the DIV appears...

Is there a solution for resolve this ?

Btw, I think the code is quite heavy. Is it possible to make a more compact version?

Big thanks all :-)




Aucun commentaire:

Enregistrer un commentaire