Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Select option remain selected after submit/refresh

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

JSFIDDLE

like image 321
Mark Gerryl Mirandilla Avatar asked Mar 13 '17 23:03

Mark Gerryl Mirandilla


2 Answers

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!

like image 149
Bango Avatar answered Oct 27 '22 06:10

Bango


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/

like image 44
Bryan Dellinger Avatar answered Oct 27 '22 07:10

Bryan Dellinger