I’m trying to show an alert box when anything is selected from a select box but the alert message disappears before anyone can “confirm” It appears for only a second or so then refreshes the page without allowing the select change.
Well you are redirecting on change, which obviously means that you are leaving the current page. In terms of UX (and good manners in general), I’d suggest only to change the location when the user explicitly confirms the selection by clicking a button or something, like e.g.
var currency = document.getElementById('currency-selector');
var confirm = document.getElementById('confirm');
confirm.addEventListener('click', function() {
window.location.href = currency.value;
});
Otherwise the user might be a bit surprised where the redirect is coming from – in fact, you didn’t take it into account yourself. They might even suspect some vicious script running and leave instantly (I would).
But as noted above, this won’t work if you’re simultaneously redirecting to another page. Maybe you could use a confirm instead of an alert, and redirect if the user accepts, like
var currency = document.getElementById('currency-selector');
var confirmed = confirm('During checkout all charges will be in US dollar');
if (confirmed) window.location.href = currency.value;
This way the user is getting the message, and still has a chance to return to the select without having to use the back button.
Ah okay… so you’re generating a new page on the server with the new currency? In this case you could send another POST parameter informing the backend that it should include an according message in the page.
Then there’s something going wrong indeed… if you show us the code, we can certainly help you sort that out. :-)
Apart from the backend solution, another way would be to set some value of the session storage accordingly, like
var currency = document.getElementById('currency-selector');
var showMessage = sessionStorage.showMessage;
if (showMessage) {
alert('During checkout all charges will be in US dollar');
sessionStorage.showMessage = false;
}
currency.addEventListener('change', function() {
sessionStorage.showMessage = true;
window.location.href = currency.value;
});
But again, I’d strongly suggest to ask the user to confirm this, even if it’s just a refresh, or an (almost) identical page for that matter.
Hopefully only for debugging purposes as that is the only use that now has - it displays additional debugging options in some browsers and can also be turned off completely.