开发者

Javascript - Remember Selected Option

I have a webpage thats created by javas开发者_如何学编程cript injections and one of my pages has a dropdown shown below:

html +="<select name='Sort' id='Sort' onchange='sortSwitch(document.getElementById(\"Sort\")[document.getElementById(\"Sort\").selectedIndex].value);     display(document.getElementById(\"searchQuery\").value);return false;'>\n";  
  html +="<option></option>\n";  
  html +="<option value='4'>Smallest First</option>\n";  
  html +="<option value='5'>Largest First</option>\n";  
  html +="<option value='6'>A-Z</option>\n";  
  html +="<option value='7'>Z-A</option>\n";  
  html +="</select>";  

The dropdown filters the information displayed on the page by passing the selected option to a switch function and another function reloads this information. However, when the javascript page loads again, it starts off with the blank option.

Does anyone know of a good way to remember the last sort selected? For example, if I sort with "Smallest First" and then the page refreshes, the box will show "Smallest First" as apposed to the blank. I know there is an "option selected" attribute, but I need it to be dynamic. I feel like it is something trivial, yet I can't seem to put my finger on it.

Thanks in advance!


Here's an article on Cookies in JavaScript which contains an explanation of how they work, along with functions to read, write and delete cookies.

Using those functions you'd get the selected value and write the cookie to save the value like this:

var select = document.getElementById("Sort");
var selectedItem = select.options[select.selectedIndex].value;
createCookie("selectedItem",selectedItem);

then read the cookie to retrieve the value and select the option in the select box, like this:

var selectedItem = readCookie("selectedItem");
var select = document.getElementById("Sort");
select.value = selectedItem;


You need to use cookies. or some session variables on the server side to save the values that were selected.

I use this jQuery cookie plugin

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜