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 ) {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.
//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;
}
}
}
function validateFields( f ) {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.
//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;
}
}
}
Copyright © 2000 - 2024 Jake Howlett of Rockall Design ltd. This article was printed from codestore.net