Skip to content

Instantly share code, notes, and snippets.

@mortenjust
Created March 25, 2012 12:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mortenjust/2193225 to your computer and use it in GitHub Desktop.
Save mortenjust/2193225 to your computer and use it in GitHub Desktop.
save radio buttons with localstorage jquery javascript
// 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>
@sandrina-p
Copy link

in chrome says error Uncaught SyntaxError: Unexpected token ILLEGAL :/

@Shaun-YUDU
Copy link

Shaun-YUDU commented Jun 5, 2018

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})
        );
    });
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment