javascript - Restore HTML form state for cascade controls when hitting F5 -
in page http://carmen-rails-demo.herokuapp.com/ there example country / state selection common in web forms.
let's suppose select united states , colorado , after hit f5. in scenario country code remembered, not state code, because it's loaded ajax.
how can save state , restore after page refresh f5?
you can use localstorage save country , code, this:
$('.country').change(function() { var country = $(this).val(); localstorage.setitem('country', country); $.get('states', {country: country}, function(data) { localstorage.setitem('states', json.stringify(data)); var $states = $('.states'); data.foreach(function(state) { $states.append('<option value="'+state.value+'">' + state.value + '</option>'); }); }); }); $('.states').change(function() { localstorage.setitem('state', $(this).val()); }); var country = localstorage.getitem('country'); if (country) { $('.country').val(country); } var states = localstorage.getitem('states'); if (states) { states = json.parse(states); var $states = $('.states'); states.foreach(function(state) { $states.append('<option value="'+state.value+'">' + state.value + '</option>'); }); var state = localstorage.getitem('state'); if (state) { $states.val(state); } }
Comments
Post a Comment