1

I am building a dropdown menu for my mobile view of my site. When the user selects an option it goes to a new url that has information specific to that choice, however I need the option to have the selected value afterwards, as it is currently showing the wrong option after the page loads

HTML:

    <select class="location-choices">
    <option id="subnav_Dallas" class="li1 first_child">Dallas</option>
    <option id="subnav_Atlanta" class="li1 active">Atlanta</option>
    <option id="subnav_Denver" class="li1" selected="">Denver</option>
    <option id="subnav_Indianapolis" class="li1">Indianapolis</option>
    <option id="subnav_San Jose" class="li1">San Jose</option>
</select>

JQuery:

$('.location-choices').on('change', function () {
    // drop down for locations
    // bind change event to select
    var url = "/locations-hours/" + $(this).val(); // get selected value
    url = url.replace(' ', '-');
    window.location = url; // redirect
    $('.location-choices1  option[href^="/locations-hours/' + location.pathname.split("/")[1] + '"]').addClass('active'); //set the dropdown to active
  });
});

1 Answers1

0

window.location = url; is going to navigate the browser page to the new url so the next line of your script will accomplish nothing. You can store the value of the selected url in localStorage or sessionStorage and then set it on page load.

You can do something like this:

//on page load, check if we have a value to set the drop down
$(function(){
    //this can be changed to use sessionStorage so it doesn't persist past session expiration
    //If the localStorage has the key, set the drop down
    const selecteduri = localStorage.getItem("selecteduri");
    if(selecteduri != null){
       $('.location-choices1  option[href^="/locations-hours/' + selecteduri + '"]').addClass('active'); //set the dropdown to active
    }
});

$('.location-choices').on('change', function () {
    //set value to localStorage
    localStorage.setItem('selecteduri', $(this).val());
    // drop down for locations
    // bind change event to select
    var url = "/locations-hours/" + $(this).val(); // get selected value
    url = url.replace(' ', '-');
    window.location = url; // redirect   
});
Ryan Wilson
  • 8,662
  • 1
  • 19
  • 34