I've been encountering issues with implementing onbeforeunload events to alert users when they attempt to navigate away from a page with unsaved form data. Despite creating a basic page, the functionality is inconsistent. There are times when it correctly warns me about leaving or reloading the page, but other times it fails to do so, even when there are no changes in the form. I've reviewed similar queries and it seems like my approach is correct. What am I missing?
<html>
<body>
<script>
window.onload = function() { doRecord(); };
window.onbeforeunload = function() { return doCheck(); };
setTimeout( doCheck, 5000 );;
var storeValue = "";
function doRecord()
{
var inp = document.getElementById( "theinput" );
storeValue = inp.value;
console.log( "Executing doRecord" );
}
function doCheck()
{
console.log( "Executing doCheck" );
var inp = document.getElementById( "theinput" );
console.log( "Comparing '" + storeValue + "' to '" + inp.value + "'" );
if ( storeValue != inp.value )
{
console.log( "It has changed" );
return "Are you sure that you want to leave this page, value has changed";
}
else
{
console.log( "It's OK" );
return null;
}
}
</script>
<h3>Form</h3>
<form id="myform" method="post" action="process.php" onsubmit="window.onbeforeunload = null" >
<input type="text" size="20" name="sometext" id="theinput" value="Change This" />
<p>
<input type=submit />
</form>
</body>
</html>