I am trying to save an options tag value to local storage. After saving its value to local storage I would like to be able to set the options tag to the option the user sele
Because your option values are integers, in this case, I would check against the value of the option, not the textual contents of the option element.
Here's a solution that works if you have incremental numerical option values, starting from zero:
DEMO
HTML:
<select name="fruit" id="fruit">
<option value="0">Apple</option>
<option value="1">Guava</option>
<option value="2">Mango</option>
<option value="3">Grapes</option>
</select>
And your JS would be:
document.getElementById("fruit").onchange = function() {
localStorage.setItem('fruit', document.getElementById("fruit").value);
}
if (localStorage.getItem('fruit')) {
document.getElementById("fruit").options[localStorage.getItem('fruit')].selected = true;
}
Its because your values and text are different for your select options. Try:
<select name="fruit" id="fruit">
<option value="Apple">Apple</option>
<option value="Guava">Guava</option>
<option value="Mango">Mango</option>
<option value="Grapes">Grapes</option>
</select>
document.getElementById("fruit").onchange = function() {
localStorage['fruit'] = document.getElementById("fruit").value;
}
window.onload= function(){
if(localStorage['fruit'])
document.getElementById("fruit").value = localStorage['fruit'];
}
Looks to me like you are storing the value of the selection in local storage, but then trying to use the option text to compare against. Maybe I'm misunderstanding how your application is working.
Anyway, this snippet should get your value selected properly (for the Guava fruit):
$("#fruit option[value='2']").attr("selected","selected");
If you must set the options tag by the text of the option (Guava):
$("#fruit option").each(function(){
if ($(this).text() == "Guava")
$(this).attr("selected","selected");
});