SEARCH
0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
Prev | Current Page 89 | Next

Jonathan Snook, Aaron Gustafson, Stuart Langridge, and Dan Webb

"Accelerated DOM Scripting with Ajax, APIs, and Libraries"

call(element)});
}
}
CHAPTER 2 n HTML, CSS, AND JAVASCRIPT 47
Cancelling Behavior
Now that the events are being called, you sometimes need to cancel the event. For example, if
you are doing form validation and the user has entered invalid data, you need to be able to tell
the browser to stop the form from submitting.
Let??™s take another look at the passcode example:
var passcode = document.getElementById("passcode");
passcode.regexp = /^[0-9]+$/;
document.getElementById("frm").onsubmit = function(){
var passcode = document.getElementById("passcode");
if(!passcode.regexp.test(passcode.value))
{
alert('Not a valid passcode');
return false;
}
}
You??™re not using the event listener approach here; instead, you attached the event handler
directly to the element. When you attach it directly to the element, you can return false to
cancel the default behavior of the element. In other words, if you attached an event handler to
a link, you could prevent the link from being followed and (as in the passcode example) prevent
the form from submitting.
When you use event listeners, you can??™t cancel the behavior in this way. However, the
DOM event object gives you a way around this: preventDefault(). Let??™s rewrite the passcode
example to use event listeners:
var passcode = document.getElementById("passcode");
passcode.regexp = /^[0-9]+$/;
function isPasscodeValid(evt)
{
var passcode = document.


Pages:
77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101
druga wojna światowa Free English grammar and study guid hotel jelenia góra Russian bride counter strike 1.6