Technology Programming

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..


<title>Example F01</title>
<form action="#">
<label for="email">Email: l</label>
<input type="input" id="email" name="email" value="" /><br>
<input type="submit" value="Submit" />
<script type="text/javascript" src="exampleF01.js"></script>


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

Leave a reply