簡體   English   中英

提交/刷新后,選擇選項保持選中狀態

[英]Select option remain selected after submit/refresh

我正在進行注冊,我有國家和州的領域。

我的問題是我提出的國家和國家在提交后沒有保留。

我試過這個

<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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM