I have a select box with 10 options. Each time you select an option it sets in the localstorage the value you selected with id "select1".
For example: If you select the first option you get in the localstorage: Key: Emailclient - Value: Option1.
Now, Iom trying to make the value of the localstorage, the selected attribute in the select form.
This is what I tried but doesn't seem to work:
if (localStorage.getItem("Select1") == "Option1"){
$('#selectbox').val("Option1").attr("selected");
}
What I'm I doing wrong?
EDIT:
This is my code:
<select id="selectbox" >
<option>Default</option>
<option>Option 1</option>
<option>Option 3</option>
<option>Option 3</option>
<option>Option 4</option>
<option>Option 5</option>
<option>Option 6</option>
</select>
Thanks
This works:
This is all you should need:
I've updated a previous fiddle for an example: http://jsfiddle.net/uY7ck/1/
EDIT: In the code you posted originally, assuming you are setting localStorage with the same select box, you would be comparing "Option1" (no space) with "Option 1" (space). That comparison will never work, so the option would never be selected.
On further review, it looks as though you wanted something more fully feature link
I think you might be looking for something like this. http://jsfiddle.net/tnPU8/3/
It loops through the options of the select box and compares their values with the values of
b
. If they are equal the index of the select box is changed so that the option that contains the value ofb
is displayed.Edit: Using
localStorage
http://jsfiddle.net/tnPU8/7/Try this:
if you are using a version of jQuery older than 1.6, replace
.prop
with.attr
Edit: more dynamic version