Home > Software engineering >  Persistent selected option on page reload
Persistent selected option on page reload

Time:04-13

I am trying to persist a selected option in a select element on the page reload. My select gets populated dynamically and once an item get selected I need it to append the value of the option to the URL and trigger a window.location to reload the page.

I am trying to do it with jQuery but would not be opposed to do only with plain JS if that's possible. This is what I've tried but the select option keeps getting back to the very first one on every page reload.

Does anyone have an idea what might be wrong here? Thank you!

$(function(){
    var storedValue = localStorage.getItem('selectedProject');
    if(storedValue != null){
        $("#projectsList").first().find(":selected").removeAttr("selected");        
        $("#projectsList").find("option").each(function () {
                if ($(this).val() == storedValue) {
                    $(this).attr("selected", true);
                }
            });
    }
    $('#projectsList').change(function () {
        localStorage.setItem("selectedProject", $("#projectsList").first().val());
        window.location = window.location.href   "?project="   localStorage.getItem('selectedProject');
    });

    $('#projectsList').change(function () {
         var currValue = $(this).val();
         localStorage.setItem('selectedProject', currValue );        
    })
    // set stored value when page loads
    .val(storedValue)

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="projectsList"  data-show-subtext="true" data-live-search="true" data-width="35%">
   <option value="value1" data-tokens="value1">value1</option>
   <option value="value2" data-tokens="value2">value2</option>
   <option value="value3" data-tokens="value3">value3</option>
</select>

CodePudding user response:

You have two .change handlers, and the one that reloads the page, always sets the localstorage to the first item option in your list.

Just using a single .change handler should solve your problems.

  $("#projectsList").change(function () {
    var currValue = $(this).val();
    localStorage.setItem("selectedProject", currValue);
    window.location =
      window.location.href   "?project="   localStorage.getItem("selectedProject");
  }).val(storedValue);
  • Related