Created
March 25, 2012 12:12
-
-
Save mortenjust/2193225 to your computer and use it in GitHub Desktop.
save radio buttons with localstorage jquery javascript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this in doc ready | |
$(function() | |
{ | |
$('input[type=radio]').each(function() | |
{ | |
var state = JSON.parse( localStorage.getItem('radio_' + $(this).attr('id')) ); | |
if (state) this.checked = state.checked; | |
}); | |
}); | |
$(window).bind('unload', function() | |
{ | |
$('input[type=radio]').each(function() | |
{ | |
localStorage.setItem( | |
'radio_' + $(this).attr('id'), JSON.stringify({checked: this.checked}) | |
); | |
}); | |
}); | |
for this in html | |
<form method="post"> | |
<input type="radio" name="foo" id="foo1" />foo1<br /> | |
<input type="radio" name="foo" id="foo2" />foo2<br /> | |
<input type="radio" name="bar" id="bar1" />bar1<br /> | |
<input type="radio" name="bar" id="bar2" />bar2<br /> | |
</form> | |
|
Was an issue with the brackets
the following works
$(function(){
$('input[type=radio]').each(function(){
var state = JSON.parse( localStorage.getItem('radio_' + $(this).attr('id')) );
if (state) this.checked = state.checked;
});
});
$(window).bind('unload', function(){
$('input[type=radio]').each(function(){
localStorage.setItem('radio_' + $(this).attr('id'), JSON.stringify({checked: this.checked})
);
});
});
Hello from the future! :) This works for both radiobuttons and checkboxes.
$(function () {
$('input[type=radio], input[type=checkbox]').each(function () {
var state = JSON.parse(localStorage.getItem('rc_' + $(this).attr('id')));
if (state) this.checked = state.checked;
});
});
$(window).bind('unload', function () {
$('input[type=radio], input[type=checkbox]').each(function () {
localStorage.setItem('rc_' + $(this).attr('id'), JSON.stringify({ checked: this.checked })
);
});
});
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
in chrome says error Uncaught SyntaxError: Unexpected token ILLEGAL :/