Reputation: 49
Hello I have made an app, in which all of the radio button state is saved in local storage. All of the radio buttons have a values, but once I send the saved radio button values, I receive only 0, instead of the radio button values. But if i press at least one radio button, all of the values are normal. I have written a scrip if a radio button is checked, then an element will receive a value. That script works fine. So I came up to the conclusion, that my jQuery code isn't working properly. Here is the jquery code, that save the radio button state.
$(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})
);
});
});
Upvotes: 0
Views: 67
Reputation: 979
(I just saw you fixed it, but I'll still post this suggestion because it simplifies your code.)
Since you're dealing with radio buttons, I would just store the selected value. No need to explicitly loop over all buttons.
$(function()
{
var value = localStorage.getItem('selected_radio');
$('input[type=radio][value=' + value + ']').prop('checked', true);
$(window).bind('unload', function()
{
localStorage.setItem('selected_radio', $('input[type=radio]:checked').first().val());
});
});
Upvotes: 1