javascript - Keep selected value of drop down list after page refresh - Stack Overflow

I have a button to filter a list based on the selections from several drop-down values. However I am ru

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.

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.

Share Improve this question asked Apr 19, 2014 at 15:23 user3148224user3148224 111 gold badge1 silver badge2 bronze badges 2
  • You can either go with cookies or the html5 local storage API – bobthedeveloper Commented Apr 19, 2014 at 15:25
  • The script that creates the page can add the SELECTED attribute to the options that it used. – Barmar Commented Apr 19, 2014 at 15:26
Add a ment  | 

1 Answer 1

Reset to default 3

You can use the HTML5 localStorage api (http://www.w3schools./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.

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1742361829a4429541.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信