In browsers later than Internet Explorer 4, Opera 5 and Netscape 6 you can assign your own attributes to elements and then refer to their values in your JavaScript functions. Take the following input element as an example:
<input name="HomeTown" type="text" size="15" errorMsg="You need to enter a value in the Home Town field" required>
You should recognise the first three attributes as being standard HTML. The next two aren't and have been made up. They are used in the following example of how to validate fields. We could create a function that looped through all elements on a form and used the getAttribute method to check whether it was required and then if empty returned the error message.
function validateRequiredFields(){Can you see how useful this could be yet? No!? Well, let's take a look at another example and see if you can't be swayed. Let's say that lots of the fields on your form need a help function. Why not add an attribute called "help" to each of the fields and then use the getAttribute method again. Consider the following field:
var frm = document.forms[0];
with (frm) {
for (var i=0; i < elements.length; i++) {
if ( elements[i].getAttribute('required') != null ) {
if ( elements[i].value == '') {
alert( elements[i].getAttribute('errorMsg') );
elements[i].focus();
return false;
}
}
}
}
return true;
}
Name | ? |
Phone | ? |
Home Town | ? |
function getFieldHelp( fldName ) {Whilst the above two examples are helpful in their own ways (well, I think so anyway ;-), hopefully they demonstrate how we can use the getAttribute method with other HTML elements to make them a lot more powerful and give us lots more options when working with JavaScript.
var fld = eval("document.forms[0]." + fldName );
if ( fld == null )
return alert('Field of that name cannot be found');
var hlp = fld.getAttribute('help');
if ( hlp == null || hlp == "")
return alert('No help has been defined for this field');
alert( hlp );
fld.focus();
}
var fld = eval("document.forms[0]." + fldName );
var fld = document.getElementById( fldName );
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net