我有这个HTML
<select id="drpRequestCategories" class="form-control" Width="100%">
<option value="-1">All</option>
</select>
这是我填写Select from it
的函数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-我在每个树视图节点上调用此函数,因此当我删除此
时$("#drpRequestCategories").empty();
它不会删除旧的下拉列值,但会将新值附加到旧值。
答案 0 :(得分:0)
好的,首先使用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
}