1

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.

user3148224
  • 11
  • 1
  • 1
  • 2

1 Answers1

3

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.

Abhishek Gurjar
  • 7,426
  • 10
  • 37
  • 45
Andrei CACIO
  • 2,101
  • 15
  • 28
  • Could you show me the code you tried so I can see why it backfires? – Andrei CACIO Jul 17 '14 at 07:20
  • can you answer this question: http://stackoverflow.com/questions/43631167/retain-the-dropdown-value-after-the-page-is-refresh-or-move-to-another-page-in-a/43631420#43631420 – Vinoth Apr 26 '17 at 10:45
  • worked perfectly, thanks. Further, didn't know about localStorage... very interesting! Andrei CACIO – carles Aug 24 '20 at 12:24