I am using the functionality below on a drop-down menu:
- The drop down menu changes the used currency and therefore changes a price of items into that currency.
When the drop-down is used, the code below also adds the content from the "title" tag of the selected currency into a Text Area (id="showTitle").
SessionStorage is used because the drop-down refreshes the page in a new currency and without sessionStorage the text area on the new page would be empty.
SessionStorage reloads the exact same content back into the text area everytime the page is refreshed. The only way to change the content
is through use of the dropdown.
So far all is well. But now for the problem.
With Safari (mac) as the browser: if the user changes currency (let's say from Euro to US Dollars) and then uses the page back function of the browser, the price is changed back to the previous price in Euro, but the text area still shows "US Dollars", because it is loaded by sessionStorage. This only seems to occur with Safari. Has anybody got a way to solve this?
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="currency select" title="Currency Selector">
<select name="currency" id="currencyList" value="GO">
<option value="" disabled="disabled" selected="selected" none="">$ € £</option>
<option value="/session/currency/usd/" title="US Dollar">USD</option>
<option value="/session/currency/eur/" title="EURO">EUR</option>
</select>
<textarea id="showTitle"></textarea>
</form>
<script>
$(document).ready(function(){
var field = document.getElementById("showTitle");
var savedValue = sessionStorage.getItem("autosave");
// See if we have an autosave value
// (this will only happen if the page is accidentally refreshed)
if (savedValue) {
// Restore the contents of the text field
field.value = savedValue;
//set dropdown to session value
$('#currencyList option[title="'+ savedValue + '"]').prop('selected', true);
}
// Listen for changes in the text field
field.addEventListener("input", function() {
// And save the results into the session storage object
sessionStorage.setItem("autosave", this.value);
});
$(document).on('change','#currencyList',function(){
//get text
var result = $("option:selected",this).attr('title');
//set field
$(field).val(result);
//set session storage item
sessionStorage.setItem("autosave", result);
//redirect
window.document.location.href=this.options[this.selectedIndex].value;
});
});
</script>
</body>
</html>