javascript - Why it is not saving values? -
hello have made app, in of radio button state saved in local storage. of radio buttons have values, once send saved radio button values, receive 0, instead of radio button values. if press @ least 1 radio button, of values normal. have written scrip if radio button checked, element receive value. script works fine. came conclusion, jquery code isn't working properly. here jquery code, save 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}) ); }); });
(i saw fixed it, i'll still post suggestion because simplifies code.)
since you're dealing radio buttons, store selected value. no need explicitly loop on 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()); }); });
Comments
Post a Comment