How to use LocalStorage on last HTML select value

后端 未结 2 1829
孤城傲影
孤城傲影 2020-12-19 18:19

How can I set/retrieve the last selected value of a select drop-down with JavaScript? I\'m trying to create an onchange function on a select drop-down that that sets the sel

相关标签:
2条回答
  • 2020-12-19 18:49

    The values in your HTML were wrong

    <select class="testSelect">
        <option value="test1">test1</option>
        <option value="test2">test2</option>
        <option value="test3">test3</option>
        <option value="test4">test4</option>
    </select>    
    

    Javascript

    var select = document.querySelector(".testSelect");
    var selectOption = select.options[select.selectedIndex];
    var lastSelected = localStorage.getItem('select');
    
    if(lastSelected) {
        select.value = lastSelected; 
    }
    
    select.onchange = function () {
       lastSelected = select.options[select.selectedIndex].value;
       console.log(lastSelected);
       localStorage.setItem('select', lastSelected);
    }
    

    http://jsfiddle.net/2MPPz/1/

    0 讨论(0)
  • 2020-12-19 18:51

    You have at least two problems in your code.

    1. The first one is an scope problem: The lastSelected variable is local defined in your function. You must define as global variable.

    2. The second one is that the first parameter of setItem & getItem methods should be a String

    So your corrected code looks like:

    var lastSelected;
    
    var select = document.querySelector(".testSelect");
    var selectOption = select.options[select.selectedIndex];
    var getLast = localStorage.getItem('select', lastSelected);
    selectOption = getLast;
    
    
    select.onchange = function () {
       lastSelected = select.options[select.selectedIndex].value;
       localStorage.setItem('select', lastSelected);
     };
    
    0 讨论(0)
提交回复
热议问题