Pergunta

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?

Foi útil?

Solução

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>

Outras dicas

Possible duplicate https://stackoverflow.com/questions/8861181

Modern browsers implement something known as back-forward cache (BFCache). When you hit back/forward button the actual page is not reloaded (and the scripts are never re-run).

If you have to do something in case of user hitting back/forward keys -- listen for BFCache pageshow and pagehide events.

A pseudo jQuery example:

$(window).bind("pageshow", function() {
  // update hidden input field
});
<select onchange="window.open(this.options[this.selectedIndex].value,'_top');this.value=''">
    <option value="" selected>Default Value</option>
    <option value="/item1">Item 1</option>
    <option value="/item2">Item 2</option>
    <option value="/item3">Item 3</option>
</select>
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top