0

I have a select menu that I am attempting to implement on my page for a user to select a country.

My current options are Canada, United States and Global. I am attempting to add the selected attribute on Canada when the page loads so Canada is by default the country selected. This is working as expected but I noticed if I selected another country for example "United States" visit another page on the website and go back via the back arrow the country I selected before redirecting in this case "United States" is still the selected country and not Canada.

If I inspect I see that Canada has the selected attribute, but United States is still shown as the one selected.

I've attempted to add

  document.getElementById("country-select").selectedIndex = -1;

Which I belive should remove the selected attribute but this is not working.

How can I reset my select drop down menu and display Canada by default even after returning back to the page.

I don't know if I will be able to re-create my issue on a code snippet but

Here is my code snippet:

    document.getElementById("country-select").selectedIndex = -1;


let selectedCountry = document.getElementById(124);
     // set Canada as default selected country
    selectedCountry.setAttribute('selected', 'true')
v    <select name="country" id="country-select">
          <option id="0" value="0">Global</option>
     <option id="1" value="1">United States</option>
      <option id="124" value="124">Canada</option>
  </select>
kurtixl
  • 419
  • 4
  • 17
  • 1
    Does this answer your question? [Select menu not being restored when Back button used](https://stackoverflow.com/questions/4370819/select-menu-not-being-restored-when-back-button-used) – Ashique Oct 04 '21 at 22:41

1 Answers1

0

You can set the selected option when the user navigates away from the page.

This is accomplished by listening for the beforeunload event:

window.onbeforeunload = function(){
  document.getElementById("country-select").value = "124";
}
Spectric
  • 30,714
  • 6
  • 20
  • 43