Daniel
Daniel

Reputation: 4342

restore dropdown selection after refresh local storage

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 selected. I have tried the follow, but I am only able to save the value. I have trouble changing the select tag to the users selected value.

<select name="fruit" id="fruit">
    <option value="1">Apple</option>
    <option value="2">Guava</option>
    <option value="3">Mango</option>
    <option value="4">Grapes</option>
</select>

document.getElementById("fruit").onchange = function() {
 localStorage.setItem('fruit', document.getElementById("fruit").value);
}

if (localStorage.getItem('fruit') === "Guava") {
 document.getElementById("fruit").setAttribute('Selected', 'Guava');
}

Upvotes: 2

Views: 13487

Answers (3)

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

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'];
    }

Upvotes: 3

Dani P.
Dani P.

Reputation: 103

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;
}​

Upvotes: 1

Tim A
Tim A

Reputation: 811

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");
});

Upvotes: 0

Related Questions