简体   繁体   中英

How Can I keep the dropdown last selected on refresh page

I have this 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. 2- I call this function on every treeview node change so when I remove this

$("#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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM