Reputation: 13
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
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:
I hope it helps :)
Upvotes: 0
Reputation: 15210
something like
{if (this.value == 'variable') {this.checked="checked";}}
Upvotes: 1
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