I have this html content:
<div class="myClass" style="display:none">
<table class="table table-hover">
.....
</table>
</div>
As you can see this is a table which is hidden
I have a checkbox to show this if the checkbox is checked
<label class="switch">
<input type="checkbox" id="test" onclick="toggle('.myClass', this)" autocomplete="on" ></legend>
<div class="slider round"></div>
</label>
<script language="JavaScript">
function toggle(className, obj) {
var $input = $(obj);
if ($input.prop('checked')) $(className).show(1000);
else $(className).hide(1000);
}
</script>
As you can see if checkbox is checked it will be shown and if it's unchecked it will hide my div
everything works great.
Now if I reload this page I want to keep the checked checkbox if it was checked or if it was unchecked I got it this way:
<script>
$(function(){
var test = localStorage.input === 'true'? true: false;
$('input').prop('checked', test || false);
});
$('input').on('change', function() {
localStorage.input = $(this).is(':checked');
if ($(this).prop('checked')) {
$(className).show(1000); //checked
}
console.log($(this).is(':checked'));
});
</script>
Now my problem is
when I reload the page if the checkbox is checked it's not showing the content.... so I have to uncheck it and check it again to make it work.
Is there a possible way to reload the page and keep my content shown if the checkbox is checked?
EDIT
thanks to @nnnnnn as answered before I got this working :
<label class="switch">
<input type="checkbox" id="test" ></legend>
<div class="slider round"></div>
</label>
<div class="myClass" style="display:none">
<table class="table table-hover">
...
</table>
<script>
$(function(){
$('#test')
.prop('checked', localStorage.input === 'true')
.on('click', function() {
localStorage.input = this.checked;
if (this.checked) {
$('.myClass').show(1000); //checked
} else {
$('.myClass').hide(1000);
}
})
.trigger('change');
});
</script>