繁体   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