user1910542
user1910542

Reputation: 13

Retain checkbox state

I have used the following code to retain the selection of a dropdown menu upon the refresh of a page.

$("#form_Selection > option").each(function() {
    if (this.value == 'variable') { 
        this.selected=true; 
    }
});

I am having a hard time configuring similar code that will retain the state of a checkbox after a refresh. Any ideas?

Upvotes: 1

Views: 423

Answers (3)

AlexStack
AlexStack

Reputation: 17381

For saving the state of all checkboxes using :checkbox and prop('checked'), you can use sessionStorage:

$(':checkbox').each(function(index,element){
    //save the 'checked' property of every checkbox
    if ( $(this).prop('checked') ) {
        sessionStorage['checked-checkboxes']=sessionStorage['checked-checkboxes'] + ',';
    }
}

And then when the page is loaded:

var checkedCheckboxes = sessionStorage['checked-checkboxes'];
//if there's anything saved in the sessionStorage for checked checkboxes
if ( checkedCheckboxes ) {
    var checkedCheckboxesNames = checkedCheckboxes.split(',');
    for( var i=0; i < checkedCheckboxesNames; i++ ) {
        $( '#' + checkedCheckboxesNames[i] ).prop( 'checked', true );
    }
}

The idea is simple: when saving, save the id of all the checkboxes which are saved, and when loading, get all those ids and set the checkboxes.

Of course you can replace sessionStorage with localStorage if you want permanent storage. Please note that:

  • all checkboxes must have an id to be identified with this algorithm.
  • there shouldn't be any other variable in the storage that uses the same key (a prefix can be used to eliminate side effects).

I hope it helps :)

Upvotes: 0

user160820
user160820

Reputation: 15210

something like

   {if (this.value == 'variable') {this.checked="checked";}}

Upvotes: 1

Christian Burtchen
Christian Burtchen

Reputation: 13

How would the following work (I've not re-printed the logic part of your code, just setting the checkbox $(this).attr('checked', true);

Upvotes: 1

Related Questions