PhpRiot
Become Zend Certified

Prepare for the ZCE exam using our quizzes (web or iPad/iPhone). More info...


When you're ready get 7.5% off your exam voucher using voucher CJQNOV23 at the Zend Store

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:

Listing 8 the onclick event on all links on a page (listing-8.js)
$$('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).

Other Options

In This Article


Additional Files