[英]How Can I keep the dropdown last selected on refresh page
I have this HTML 我有这个HTML
<select id="drpRequestCategories" class="form-control" Width="100%">
<option value="-1">All</option>
</select>
and here is the function I fill the 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);
});
}
when I click on Search button on my page 1-it clear this dropdownlist but I need to keep the last selected value. 当我单击页面1上的“搜索”按钮时,它会清除此下拉列表,但我需要保留最后选择的值。 2- I call this function on every treeview node change so when I remove this 2-我在每个treeview节点更改时都调用此函数,所以当我删除此函数时
$("#drpRequestCategories").empty();
it doesn't remove the old dropdown values but append the new values to the old . 它不会删除旧的下拉值,而是将新值附加到旧的。
Ok first using localstorage set a key holding the last selected item ,while every node change first empty the select box and use the localstorage item to fill the box again 首先,使用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.