<html>
<head>
<title>Prevent accidental page reload</title>
<script type="text/javascript">
/* check to see if form field values have changed */
function checkForFormChanges()
{
var l_oForm = document.getElementById('mainForm');
var l_pInputs = l_oForm.getElementsByTagName('INPUT');
for (var loop=0, max=l_pInputs.length; loop<max; loop++)
{
if (l_pInputs[loop].defaultValue != l_pInputs[loop].value)
{
g_bPreventUnload = true;
break;
}
}
}
/* method to run as the page is about to unload */
function preUnload()
{
checkForFormChanges();
if (g_bPreventUnload)
{
var l_sMessage = "You made changes to the form. ";
l_sMessage += "If you continue, they will be lost.";
try
{
window.event.returnValue = l_sMessage;
}
catch(e)
{
// swallow firefox error
}
return l_sMessage;
}
}
/* clear onbeforeunload event when the form is sent */
function clearUnload()
{
if (window.detachEvent)
{
window.detachEvent("onbeforeunload", preUnload);
}
else
{
window.onbeforeunload = null;
}
}
/* initialise the page, attaching the DOM events */
function init()
{
window['g_bPreventUnload'] = false;
if (window.attachEvent)
{
window.attachEvent("onbeforeunload", preUnload);
}
else
{
window.onbeforeunload = preUnload;
}
document.getElementById('mainForm').onsubmit = clearUnload;
}
window.onload = init;
</script>
</head>
<body>
<form action="" method="get" id="mainForm">
<fieldset>
<input type="text" name="reason" value="initial"/>
<input type="submit" name="submit" value="Send Form"/>
</fieldset>
</form>
</body>
</html>