Creating dynamic references to objects

Jake Howlett, 27 October 2000

Category: JavaScript; Keywords: input object string

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.

To get around this we use the eval() function to return an Object reference to an element that has been defined as a String. So the above function would work if it were:
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.

Note: Everything that appears as a part of the parameter to the eval() function needs to be a string. In the above example f.name returns a string, whereas the following would cause an error, as f is an Object: eval(f+".Quantity"+i)