jQuery checkbox hide and show div

0 votes
asked Sep 11, 2017 by ido-beker

I have problem this work and all fine, but the checkbox not so good if I mark checkbox1 after reload it's mark the checkbox2 and checkbox1. I must help to find how this work.

Save only the checkbox mark

$(function(){        
  $('#checkbox1')
    .prop('checked', localStorage.input === 'true')
    .on('change', function() {
      localStorage.input = this.checked;
      if (this.checked) {
        $('.column_category').show(0); //checked
      } else {
        $('.column_category').hide(0);
      }
    })
    .trigger('change');
});

$(function(){        
  $('#checkbox2')
    .prop('checked', localStorage.input === 'true')
    .on('change', function() {
      localStorage.input = this.checked;
      if (this.checked) {
        $('.column_sku').show(0); //checked
      } else {
        $('.column_sku').hide(0);
      }
    })
    .trigger('change');
});


<input type="checkbox" id="checkbox1"/><label for="cbxShowHide">Categories</label>
<input type="checkbox" id="checkbox2"/><label for="cbxShowHide">SKU</label>
<input type="checkbox" id="checkbox3"/><label for="cbxShowHide">UPC</label>

2 Answers

0 votes
answered Sep 11, 2017 by marcin-szwarc

I think it's because you bind checkbox1 and checkbox2 to the same input field of localStorage. Maybe this can help:

$('#checkbox1')
  .prop('checked', localStorage.check1State=== 'true')
  .on('change', function() {
     localStorage.check1State = this.checked;
     if (this.checked) {
       $('.column_category').show(0); //checked
     } else {
       $('.column_category').hide(0);
     }
  })
  .trigger('change');
});

And something similar on second checkbox.

0 votes
answered Sep 11, 2017 by shiladitya

Here you go with a solution https://jsfiddle.net/441s41mt/1/

$('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');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="checkbox1" data-target="column_category"/><label for="cbxShowHide">Categories</label>
<input type="checkbox" id="checkbox2" data-target="column_sku"/><label for="cbxShowHide">SKU</label>
<input type="checkbox" id="checkbox3"/><label for="cbxShowHide">UPC</label>
Welcome to Q&A, where you can ask questions and receive answers from other members of the community.
...