0

so I use the below code to refresh a page on dropdownlist value changes and save the value in local storage and load it again:

<select class="CB" id="CB" disabled>
   <option value="a">a</option>
   <option value="b">b</option>
</select>


<script>
    if(localStorage.getItem('CB')){
    $('#CB').val(localStorage.getItem('CB'));
    }

    $('#CB').change(function(){
    localStorage.setItem('CB',$('#CB').val() );
    location.reload();
    });
</script>

but the code above doesn't work for checkbox for some reasons! How can do the similar thing for a checkbox?

Adrin
  • 585
  • 3
  • 11
  • 1
    The value of checkbox do not change. Their `checked` state changes. – Taplar Oct 08 '18 at 22:50
  • 1
    Possible duplicate of [Check/Uncheck checkbox with JavaScript?](https://stackoverflow.com/questions/8206565/check-uncheck-checkbox-with-javascript) – Heretic Monkey Oct 08 '18 at 22:58

1 Answers1

1

If you are using a checkbox instead of a select, you'll need to target the "checked" property.

var $CB = $('#CB');

if (localStorage.getItem('CB')) {
  $CB.prop('checked', localStorage.getItem('CB') == 'true');
}

$CB.on('change', function() {
  localStorage.setItem('CB', $CB.prop('checked'));
  location.reload();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="CB">

StackSnippets don't provide access to localStorage, so here's a JSFiddle for demonstration.

showdev
  • 28,454
  • 37
  • 55
  • 73