I'm working on a registration and I have fields for country and state.
My problem is the country and the state that I choose didn't retain after the submission.
I tried this
<script type="text/javascript"> document.getElementById('country').value = "<?php echo $_POST['country'];?>"; </script>
but didn't work.
so I tried another option using sessionStorage
$(function() { $('#country').change(function() { sessionStorage.setItem('todoData', this.value); }); if(sessionStorage.getItem('todoData')){ $('#country').val(sessionStorage.getItem('todoData')); } }); </script>
It work on the country but not in the state, the choices is still the default options.
How can I fix that.. or is there another option to to make it work.
thanks.
SAMPLE CODE
2 Answers
Answers 1
Here is a working example of the functionality you desire. I'm using localStorage like the person who answered before me.
https://jsfiddle.net/a0uj5d86/2/
//handle select changes, put new data in storage document.getElementById('country').onchange = function () { console.log('country change'); localStorage.setItem('country', this.value); populateStates('country', 'state'); }; document.getElementById('state').onchange = function () { localStorage.setItem('state', this.value); }; document.getElementById('country2').onchange = function () { localStorage.setItem('country2', this.value); };
Then in populate countries at the end I have a little diddy that goes
var selection = 'USA'; if (localStorage.getItem(countryElementId)) { console.log('found ' + countryElementId + ' in storage = ' + localStorage.getItem(countryElementId)); var selection = localStorage.getItem(countryElementId); } //select our country (default USA, or local storage if applicable) findAndSelect(countryElementId, selection); if (countryElementId == 'country') { //we just populated country, now populate states populateStates(countryElementId, stateElementId); if (localStorage.getItem(stateElementId)) { //if weve got a state to select, select it findAndSelect(stateElementId, localStorage.getItem(stateElementId)); } else { findAndSelect(stateElementId, 'Alabama'); } }
I also did some odds-n-ends refactoring to the code you had. Give it a look and get back to me with any questions!
Answers 2
are you allowed to use HTML5 local storage?
var selectedVal = localStorage.getItem('selectedVal'); if (selectedVal){ $('#mySelect').val(selectedVal) }
here is a fiddle http://jsfiddle.net/jvso1Lcc/22/
0 comments:
Post a Comment