Friday, February 23, 2007

JavaScript Warning while using the backspace button to go back

With all the new AJAX stuff around, using the back button can be disadvantageous for keeping your form values. While filling in forms it is very easy to press the backspace button by mistake while not in a input field and going back to your previous page.
So the best way is to let the user acknowledge the page transition while using the backspace button. It is possible to use an onbeforeunload event to confirm leaving the page, but this event also wants confirmation on following links and other exiting events.

I solved the program with the following javascript code:

var bConfirmExit = false;
function closeIt()
{
if (bConfirmExit)
{
event.returnValue = "Bij het verlaten van deze pagina verliest u de ingevoerde gegevens.";
}
}
function resetExit()
{
bConfirmExit = false;
}
function checkBS()
{
if (event.keyCode == 8)
{
bConfirmExit = true;
setTimeout("resetExit()",200);
}
}


and linked the following events in the body tag:

<body onbeforeunload="closeIt()" onkeydown="checkBS()">

No comments: