Take the following JavaScript function. It is meant for a form that has six fields whose names are all of the format "QuantityX" where X is a number from 1 to 6. Have a look at the code and see if you can see anything wrong with it:
function validateFields( f ) {
//var f is the form object
for ( var i = 1; i < 7; i ++) {
fieldName = "Quantity" + i ;
if ( f.fieldName.value == "" ) {
alert( 'You need to enter a value field ' + fieldName );
return false;
}
}
}Look OK ? It will cause an error ! Not because we are trying to append a number to a string (that is ok, because JavaScript is "un-typed"). It is because the variable called "fieldName" is a String, whereas in order to reference it within the structure of the DOM like that it needs to be an Object variable.function validateFields( f ) {
//var f is the form object
for ( var i = 1; i < 7; i ++) {
fieldName = eval("document." + f.name + ".Quantity" + i );
if ( fieldName.value == "" ) {
alert( 'You need to enter a value field ' + fieldName );
return false;
}
}
}The eval() funtion is not only useful when you have things like groups of fields of similar names but also when you need to reference and object when you only know its name.Copyright © 2000 - 2025 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net