JavaScript By Example
JavaScript originally provided a number of different ways by which form fields could be referenced since one of the earliest uses to which JavaScript was intended to be put was for validating the form within the web browser so as to save the person filling out the form having to wait to find out they'd entered something wrong. Most of these ways of accessing forms are no longer required given that in order to label your form fields you need to give each an id for the label to reference and can therefore access the fields directly using getElementById.
In this example we use the addEvent processing we saw in one of the event examples to attach a validateEmail function to the email field in our form so that it will be validated (according to whatever code we add into that function) as soon as the focus is moved to a different field in the form..
In this example we use the addEvent processing we saw in one of the event examples to attach a validateEmail function to the email field in our form so that it will be validated (according to whatever code we add into that function) as soon as the focus is moved to a different field in the form..
HTML
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<head>
<title>Example F01</title>
</head>
<body>
<form action="#">
<div>
<label for="email">Email: l</label>
<input type="input" id="email" name="email" value="" /><br>
<input type="submit" value="Submit" />
</div>
</form>
<script type="text/javascript" src="exampleF01.js"></script>
</body>
</html>
JavaScript
if (window.addEventListener)
addEvent = function(ob, type, fn ) {
ob.addEventListener(type, fn, false );
};
else if (document.attachEvent)
addEvent = function(ob, type, fn ) {
var eProp = type + fn;
ob['e'+eProp] = fn;
ob[eProp] = function(){ob['e'+eProp]( window.event );};
ob.attachEvent( 'on'+type, o[eProp]);
};
validateEmail = function() {
// code to validate the email address goes here
}
addEvent(document.getElementById('email'),
'blur',
validateEmail);