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 value selected in the menu).
Issue: when the user hits the Back button, the page DOM is restored from the cache but NOT the state of the select menu.
Browsers affected: Firefox and Safari (which use a back/forward cache)
Example:
<script language="javascript" type="text/javascript">
function reloadPage() {
var menu = document.getElementById("select1");
var val = menu.options[menu.selectedIndex].value;
window.location.href = 'test.html?select1=' + val;
}
</script>
<form action="#" method="get" name="form1">
<select name="select1" id="select1" onChange="reloadPage();">
<option value="A" selected>Option A</option>
<option value="B">Option B</option>
<option value="C">Option C</option>
<option value="D">Option D</option>
</select>
</form>
View this page and notice that option A is selected. Then select a different option (say option C) - the page is reloaded (with a query string, ?select1=C). Then hit the Back button - the select menu continues to show Option C as selected.
Question: Does anyone know why the select menu isn't restored and how one could solve this issue? I've used JavaScript in the past to force the form fields on a page to match the query string but there are issues with that approach (i.e., FF and Safari don't normally execute the onload event for the window when loading a page from the cache) and it seems like a hack to me.
Any suggestions?
Update: It has just occurred to me that what might be going on is the following:
So I think this isn't an issue of the browser not restoring the state of the select menu, it's an issue of timing.
This jQuery code did the trick for me
$(document).ready(function () {
$("select").each(function () {
$(this).val($(this).find('option[selected]').val());
});
})
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);
}
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With