Keep selected value of drop down list after page refresh

谁说胖子不能爱 提交于 2019-12-02 07:04:25

问题


I have a button to filter a list based on the selections from several drop-down values. However I am running into an issue whereby once the button is clicked, the page refreshes and the drop-down values are reset to the default. How could I ensure that after the refresh, the selected values persist on the drop-down?

<div><select>
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
  <option value="mercedes">Mercedes</option>
  <option value="audi">Audi</option>
  </select>

   <select>
    <option value="ford">ford</option>
    <option value="chevy">Chevy</option>
    <option value="ram">Ram</option>
    <option value="jeep">Jeep</option>
   </select>

   <button id="button" onclick="filterMyList()">Filter</button>
  </div>

Any suggestions on how this could be handled? Thanks.


回答1:


You can use the HTML5 localStorage api (http://www.w3schools.com/html/html5_webstorage.asp)

Example for your case:

$(document).ready(function() {
    // On refresh check if there are values selected
    if (localStorage.selectVal) {
            // Select the value stored
        $('select').val( localStorage.selectVal );
    }
});

// On change store the value
$('select').on('change', function(){
    var currentVal = $(this).val();
    localStorage.setItem('selectVal', currentVal );
});

Hope this helps. Keep me posted.



来源:https://stackoverflow.com/questions/23171840/keep-selected-value-of-drop-down-list-after-page-refresh

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!