restore dropdown selection after refresh local storage

前端 未结 3 1570
眼角桃花
眼角桃花 2021-01-03 12:42

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

相关标签:
3条回答
  • 2021-01-03 13:20

    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;
    }​
    
    0 讨论(0)
  • 2021-01-03 13:23

    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'];
        }
    
    0 讨论(0)
  • 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");
    });
    
    0 讨论(0)
提交回复
热议问题