我正在进行注册,我有国家和州的领域。
我的问题是我选择的国家和州在提交后没有保留。
我试过这个
<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
以下是您需要的功能的实例。我正在使用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');
}
}
我也对你的代码进行了一些可能性的重构。看看,如有任何问题请回复我!
你被允许使用HTML5本地存储吗?
var selectedVal = localStorage.getItem('selectedVal');
if (selectedVal){
$('#mySelect').val(selectedVal)
}
这是一个小提琴
http://jsfiddle.net/jvso1Lcc/22/