HomeJavaScript Page 7 - Understanding The JavaScript Event Model (part 1)
Flavour Of The Month - JavaScript
This may be news to you, but JavaScript comes with a powerfuland flexible event model, one which provides developers with astandardized way of trapping and handling client-side events likekeystrokes and mouse clicks. This two-part article takes an in-depthlook at how this event model works, demonstrating some practical (andnot-so-practical) uses of the most common event handlers.
In this case, every time the user clicks inside or outside the text field, either the onFocus() or onBlur() handler is triggered and an appropriate message displayed.
The next example reworks the one on the previous page to perform field validation when the user tabs out of each field on a form:
<html>
<head>
<script language="JavaScript">
// check name field
function checkName()
{
// if empty, pop up alert
if (document.forms[0].name.value == "")
{
alert("Please enter a valid name");
return false;
}
else
{
return true;
}
}
// check email field
function checkEmail()
{
var flag;
var str = document.forms[0].email.value;
// regex to match email addresses
var pattern =
/^([a-zA-Z0-9])+([\.a-zA-Z0-9_-])*@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-]+)+/;
var flag = pattern.test(str);
if(!flag)
{
alert ("Please enter a valid email address");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form action="submit.php" method="post">
Please enter your name.
<br>
<input type="text" name="name" onBlur="checkName()">
<p>
Please enter your email address.
<br>
<input type="text" name="email" size="25" onBlur="checkEmail()"> <br>
<input type="submit" value="Hit me!"> </form>
</body>
</html>
Another very useful event handler, especially in the context of forms, is one you've already seen before - the onClick handler. Consider the following example, which demonstrates it in the context of a radio button,