Articles
On Page Leave Notification in Javascript
January 06, 2007 (javascript, usability)
With complex multi page forms users often visit a form page, make some changes and navigate away from the page with submitting the changes. This results in lost data and user frustration.
In desktop apps a document becomes dirty once changes have been made and any attempt to close the document prompts the user to save. In the following Javascript code a form can be made dirty and prompt presented when a user forgets to submit.
The first step is to place the following javascript in the <head> tag of the page.
var isDirty = false;
window.onbeforeunload = confirmExit;
function confirmExit()
{
if (isDirty)
return "You have made changes to your form without saving them.'
}
</script>
The next bit of code goes into your submit button as an onlick event. The following is what my submit button looks like. The motivation here is to explicitly set the JS variable isDirty to false when submitting. This is because we don't want the unsaved error message to pop up during the act of saving.
The final step is to add onchange events to each field in the form to set the isDirty variable to true when changes are made. For different element types the commands are slightly different. They are as follows
For text fields, textareas, select boxes and check boxes add the following onChange event.
<textarea name=q2 rows=5 cols=50 onChange="isDirty = true;" ></textarea>
<select name=q3 onChange="isDirty = true;">
...
</select>
<input type=checkbox name=q4 value="1" onChange="isDirty = true;" />
For radio buttons add the following onClick event.
With the fields set up, any change to their value will make them dirty. If the user tries to leave the page in any way, via link, back button, close the browser, etc, an alert will prompt them. The alert will inform them that they haven't saved their changes. If they hit the Cancel button the page navigation fails and they remain on the current page, now able to hit the save button. If they click Ok they navigate to their original destination.
