Skip to content Skip to sidebar Skip to footer

Select Menu Not Being Restored When Back Button Used

Consider a web page that has a select menu with a JavaScript event handler tied to the menu's onchange event that when fired reloads the page with a new query string (using the val

Solution 1:

This jQuery code did the trick for me

$(document).ready(function () {
    $("select").each(function () {
        $(this).val($(this).find('option[selected]').val());
    });
})

Solution 2:

The snippet from @frakhoffy worked for me, but broke normal select behavior in Chrome. When hitting the page without a selected option, the select was blank even though there is not a blank option in the select. I ended up going with:

$(document).ready(function () {
  $('select').each(function () {
    var select = $(this);
    var selectedValue = select.find('option[selected]').val();

    if (selectedValue) {
      select.val(selectedValue);
    } else {
      select.prop('selectedIndex', 0);
    }
  });
});

Solution 3:

This is what happens by default in forms (not just selects): the browser will keep the last values. I wouldn't add any JavaScript code to alter this behavior unless you want to debug that code with multiple browsers.

The easiest solution, that would fix the problem in most (all?) modern browsers, is to use autocomplete="off" in the <form> tag.

Edit: See answer https://stackoverflow.com/a/14421723/1391963


Solution 4:

AFAIK the reason it's not being restored is that DOM isn't the one that was in the cache at the last time of cache-loading. The browser restores what the cached-object was on page-back. You have to maintain state yourself.

I would suggest putting a function in the body proper that will always run as the DOM is parsed (but I've not got a sample environ setup to test this scenario so I'm going on my "it should work" detector)

<script type="javascript">
  function fix_selects(){
    //do something here to ensure that the select is setup how you want. 
    //Maybe using a window location hash?
  }
  fix_selects();
</script>

Solution 5:

Here is a vanilla JS version of @Mitch's answer.

let selects = document.getElementsByTagName('select');

for (let i = 0; i < selects.length; ++i) {
    let currentSelect = selects[i];
    let selectedOption = currentSelect.querySelector('option[selected]');
    if (selectedOption) currentSelect.value = selectedOption.value;
}

Here is the performance comparison

enter image description here


Post a Comment for "Select Menu Not Being Restored When Back Button Used"