簡體   English   中英

如何保持下拉列表在刷新頁面上的最后一次選擇

[英]How Can I keep the dropdown last selected on refresh page

我有這個HTML

<select id="drpRequestCategories" class="form-control" Width="100%">
    <option value="-1">All</option>
</select>

這是我填寫的選擇功能

function filldropdownlistcategory(res) {             
    var test = $.parseJSON(res.d);
    $("#drpRequestCategories").empty();
    $(test).each(function () {               
        var option = $('<option />');
        option.attr('value', this.ServiceID).text(this.ServiceName);
        $('#drpRequestCategories').append(option);
    });
}

當我單擊頁面1上的“搜索”按鈕時,它會清除此下拉列表,但我需要保留最后選擇的值。 2-我在每個treeview節點更改時都調用此函數,所以當我刪除此函數時

$("#drpRequestCategories").empty(); 

它不會刪除舊的下拉值,而是將新值附加到舊的。

首先,使用localstorage設置保存最后一個選定項的鍵,然后每個節點更改都首先清空選擇框,然后使用localstorage項再次填充該框

//Add the onchange listener for the select box
  $("#drpRequestCategories").on('change',function(evt){
    var optionSelected=evt.target.value;
    localStorage.setItem("recent",optionSelected);
  }
//Now your function
  function filldropdownlistcategory(res){
    //empty the box
    $("#drpRequestCategories").empty();
    $(test).each(function () {               
    var option = $('<option />');
    option.attr('value', this.ServiceID).text(this.ServiceName);
    $('#drpRequestCategories').append(option);
    });
   //Once U have appended the options attach the previous list to the select box
   var prevOptions=JSON.parse(localStorage.getItem("options"));
   for(var key in options){
     var option=$('<option />')
     option.attr("value",options[key]).text(options[key])
     $("#drpRequestCategories").append(option)
   }
   //Now Select the Last selected option
   var lastSelected=localStorage.getItem("recent");
   $("#drpRequestCategories").val(lastSelected);
   //Once all the options are populated call the storeOptions Function
   storeOptions();   
 }
 //Function to store the options
 function storeOptions(){
  var options=$("#drpRequestCategories").children();
  var obj={};
  for(var i=0;i<options.length;i++){
  var optionText=options[0].value || options[0].innerHTML //Depends on         what you want
  //update the obj
  obj["option"+i]=optionText;    
}
//Now Store them in localStorage
  localStorage.setItem("options",JSON.stringify(obj))//stringify will convert the object into a string
 } 

暫無
暫無

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

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