So I was asked recently how to stop people leaving a web page without hitting the submit button on the form they were filling in.
It turns out people were registering for an event but the hastily put together form had little sense checking and a number of people had filled in the (very long) form but hadn't hit the submit button. They thought they were registered for the event but their details weren't saved.
In general, individuals may be smart but sure as hell, people are dumb dumb dumb. If there's a chance someone will do something weird with a form, you can bet they will.
Luckily, warning them when they try to navigate away from the page their on is pretty easy.
Step 1
Stick this in the head of your page:
<script language="javascript">
function unloadMsg(){
msg = "You haven't finished filling in your form."
return msg;
}
function setUnload(on){
window.onbeforeunload = (on) ? unloadMsg : null;
}
setUnload(true);
</script>
Step 2
Any button or link that should actually let them leave the page without warning should have this added to it:
onclick="window.onbeforeunload = null;"
Job done!
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Please don't leave!</title>
<script language="javascript">
function unloadMsg(){
msg = "You haven't finished filling in your form."
return msg;
}
function setUnload(on){
window.onbeforeunload = (on) ? unloadMsg : null;
}
setUnload(true);
</script>
</head>
<body>
<h1>Please Don't Go Test</h1>
<p>To test:
<ul>
<li>Try closing this page</li>
<li>Navigate to <a href="http://www.google.com">Google</a> with warning still turned on</li>
<li>Turn off warning and navigate to <a href="http://www.google.com" onclick="window.onbeforeunload = null;">Google</a></li>
</ul>
</p>
</body>
</html>