提交/刷新后,选择选项保持选中状态

时间:2017-03-13 23:17:09

标签: javascript jquery

我正在进行注册,我有国家和州的领域。

我的问题是我选择的国家和州在提交后没有保留。

我试过这个

<script type="text/javascript">
  document.getElementById('country').value = "<?php echo $_POST['country'];?>";
</script>

但没有用。

所以我尝试了使用sessionStorage的另一个选项

$(function() {
    $('#country').change(function() {
        sessionStorage.setItem('todoData', this.value);
    });
    if(sessionStorage.getItem('todoData')){
        $('#country').val(sessionStorage.getItem('todoData'));
    }
});
</script>

它适用于国家但不适用于州,选择仍然是默认选项。

我该如何解决这个问题?或者是否有另一种选择让它发挥作用。

感谢。

示例代码

JSFIDDLE

2 个答案:

答案 0 :(得分:9)

以下是您需要的功能的工作示例。我使用localStorage就像在我面前回答的那样。

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);
};

然后在最后的国家/地区,我有一点点了,

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');
  }
}

我也对你的代码进行了一些可能性的重构。看看它,如有任何问题请回复我!

答案 1 :(得分:2)

您是否可以使用HTML5本地存储?

 var selectedVal = localStorage.getItem('selectedVal');
    if (selectedVal){
       $('#mySelect').val(selectedVal)
    }

这是一个小提琴 http://jsfiddle.net/jvso1Lcc/22/

相关问题