How to use LocalStorage on last HTML select value

后端 未结 2 1837
孤城傲影
孤城傲影 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

        
    

    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/

提交回复
热议问题