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
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
As of January 16, 2020 I had a very similar issue and was unable to find a solution on Stackoverflow.
Here is what fixed this issue for me:
Update Jquery!
I updated from an older version (2.x) to 3.4.0. I went with this version since I am running bootstrap 3 and newer versions of Jquery completely break bootstrap 3 any higher than 3.4.0.
I hope this saves some people some time.
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
This jQuery code did the trick for me
$(document).ready(function () {
$("select").each(function () {
$(this).val($(this).find('option[selected]').val());
});
})
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>
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);
}
});
});