Keep selected value of drop down list after page r

2019-03-01 19:10发布

问题:

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.