Search code examples
htmldrop-down-menudefaultformsback-button

How to change a <select> element back to the default value when hitting the back button?


I have a <select> element, used for navigation. You click on it to choose a page to go to, and when clicked it goes to that page. Here is the code for it:

<select onchange="window.open(this.options[this.selectedIndex].value,'_top')">
    <option value="/item1" selected>Item 1</option>
    <option value="/item2" selected>Item 2</option>
    <option value="/item3" selected>Item 3</option>
</select>

When I use it, it goes to the page correctly, however when hitting the back button, the dropdown has the page I went to selected already. For example, if I'm on Item 1, and select Item 2, then go back to Item 1 through the browser's back button, Item 2 is selected in the list, which is kind of confusing.

How can I get it to switch back to the default value?


Solution

  • You can reset your selection box to the default value and then navigate to the new page. Here's an example of how to do that.

    <script>
    fix_ipad = function(evt){
        go_to = document.getElementById('go_to');
        go_to.selectedIndex = 0; // reset to default value before leaving current page
    };
    
    window.addEventListener("pagehide",fix_ipad,false);
    
    goto_page_and_reset_default = function(){
        go_to = document.getElementById('go_to');
        go_to_page = go_to.value;
        go_to.selectedIndex = 0; // reset to default value before leaving current page
    
        window.open(go_to_page,"_top");    
    
    }
    </script>
    
    <select onchange="goto_page_and_reset_default()" id='go_to'>
        <option value="/item1" selected>Item 1</option>
        <option value="/item2" selected>Item 2</option>
        <option value="/item3" selected>Item 3</option>
    </select>