Reminding Users to Submit Forms
Summary
In this article we looked at a simple and effective way to prevent users from navigating from a form on your web site and losing their data. We did so by handling the onbeforeunload DOM event. By using Prototype it was simple to write a reusable class that is easily invoked with a single line of code.
Note however that there may be other improvements you wish to make. When handling the onbeforeunload event all you are allowed to do is set a message that is shown in the confirm box: You can't actually handle the result of the confirm box.
For example, in addition to handling this event you may also wish to observe the onclick event on all hyperlinks on the page. This will allow you to manually display a confirmation box, meaning you can handle the return value how you please (for example, if they click OK you can proceed with the link click, or you can call Event.stop(e) to cancel it).
Doing this may allow you to add some extra functionality, such as scrolling down the page to the submit button so the user can see it. Or you could even highlight the button or even trigger JavaScript-based form validation so the user knows what they still need to complete before submitting the form.
As a starting point, to retrieve all the links on a page and observe them being clicked, you can use JavaScript like the following:
$$('a').each(function(link) { link.observe('click', function(e) { if (!confirm('Are you sure you want to leave?')) Event.stop(e); } });
Be aware however that if there are a large number of links on your page this may be processor intensive on the client computer (also remember that this doesn't deal with the user refreshing the page or closing their browser).
- Download a PDF version of this article
- View or post comments for this article
- Browse similar articles by tag: JavaScript, onbeforeunload, Prototype
-
Read related articles:
- Eight Weeks of Prototype: Week 4, Event Handling in Prototype
- Creating Sortable Lists With PHP And Ajax
- Eight Weeks of Prototype: Week 3, Prototype Data Types
- Eight Weeks of Prototype: Week 7, Other Prototype Functionality
- Eight Weeks of Prototype: Week 2, How Prototype Extends Elements
- Eight Weeks of Prototype: Week 6, Writing JavaScript Classes with Prototype
- Eight Weeks of Prototype: Week 5, Ajax with Prototype
- Eight Weeks of Prototype: Week 1, Beginning with Prototype
