mercredi 5 avril 2017

Jquery - how to keep checkbox checked and content shown when reload page?

I need really your help please..

I'm having 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 checkboxto 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?

THANKS!!




Aucun commentaire:

Enregistrer un commentaire