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

Eight Weeks of Prototype: Week 4, Event Handling in Prototype

Stopping an Event

Frequently you will want to stop an event from completing, since you are defining a method by which to handle the event, and therefore don't want the browser to use its own handling method.

The two best examples of this are for hyperlinks and forms. Firstly, let's look at links. Often you will want to perform some action when the user clicks a link, however you don't want the browser to follow the link.

Note: This is especially useful if you want to use Ajax to retrieve the page at the given link. This specific example will be shown in the fifth article of this series.

Before using Prototype, you might be more familiar with returning false from the event handler. For example, you might use <a href="..." onclick="doSomething(); return false">...</a>. By returning false in the onclick handler, the browser knows not to follow the link in the href attribute.

In order to achieve this same effect with Prototype, the Event.stop() method is used instead. Returning false from your handler method will have no effect. Calling Event.stop() tells Prototype to stop event propagation and not perform the default browser action.

Note: If you have multiple handlers for a given event, all of them will be executed regardless of whether you have called Event.stop() in any or all the handlers. I'll cover this in more detail shortly.

Listing 6 shows an example of stopping an event if required to do so. In this example, a JavaScript confirmation box is displayed to the user. If they click OK, then the link is followed, whereas clicking Cancel will result in the link not being followed.

Note: Although not specifically related to this concept, you should typically use a POST form if your action has some side-effect on your application (such as deleting data from a database) rather than a normal hyperlink.
Listing 6 Stopping an event with Event.stop() (listing-6.html)
<html>
    <head>
        <title>Stopping an event with Event.stop()</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div>
            <a href="/path/to/do/something.php" id="myLink">Do Something!</a>
        </div>
 
        <script type="text/javascript">
            function onMyLinkClick(e)
            {
                var msg = 'Are you sure you want to do this?';
 
                if (confirm(msg)) {
                    // user click ok, nothing to do - link will be followed as normal
                }
                else {
                    // user clicked cancel, stop the event
                    Event.stop(e);
 
                    // link will now not be followed
                }
            }
 
            $('myLink').observe('click', onMyLinkClick);
        </script>
    </body>
</html>

This same concept can be useful implementing JavaScript-based form validation. By observing the submit event, you can then check form values before deciding whether or not to allow the browser to submit the form.

Listing 7 shows an example of how this is achieved. In this example, I've created a form with a single text input. The validation routine (onFormSubmit()) checks if this text input is blank (we covered the blank() method in the third article of this series), and if so records an error.

To complete the event handler, we check if there are any errors (by checking the size of the errors array), and if so we stop the event from propagating and display an error message.

Note: The serialize() method is a special method for forms that allows you to easily retrieve all of the values in a single object. If true is not passed as the first argument then the data is returned as a "get" style string (which is difficult for us to validate).
Listing 7 Validating a form before deciding whether it should be submitted (listing-7.html)
<html>
    <head>
        <title>Validating a form before deciding whether it should be submitted</title>
        <script type="text/javascript" src="/js/prototype.js"></script>
    </head>
    <body>
        <div>
            <form method="post" action="/some/form/target.php" id="theForm">
                <div>
                    <input type="text" name="name" />
                    <input type="submit" />
                </div>
            </form>
        </div>
 
        <script type="text/javascript">
            function onFormSubmit(e)
            {
                // retrieve all values to check
                var values = $('theForm').serialize(true);
 
                // placeholder array for errors
                var errors = [];
 
                // check if the name was entered
                if (values.name.blank()) {
                    errors.push('Please enter the name');
                }
 
                // check if any errors were found
                if (errors.size() > 0) {
 
                    // display the errors
                    alert('There were errors:\n' + errors.join('\n'));
 
                    // prevent the form from being submitted
                    Event.stop(e);
                }
            }
 
            $('theForm').observe('submit', onFormSubmit);
        </script>
    </body>
</html>
Note: Even though form validation using JavaScript is very useful to the user, you should not be relying solely on this validation in your application. You still need to validate all values on the server-side, since it is trivial for a user to bypass the JavaScript validation.

Technically you could observe the click event on the submit button rather than the submit event on the form, however the form might be submitted using a method other than this button. For instance, if the user presses enter while filling out the text input the form will be submitted (triggering the submit event but not the button click event).

In This Article