Creating dynamic references to objects
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;
}
}
}
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 ) {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;
}
}
}
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)
form[fieldname]
With elements on a form, you can go after names as if they were numbers in an array. For example, given: <pre>var thisform = document.forms[0];</pre> then if the first element on the form is a field named "FirstField" then it can be accessed using any of the following: <pre>thisform[0] thisform.FirstField thisform["FirstField"] thisform["First" + "Field"]</pre> So to access fields Quantity1 through Quantity7 and make sure they aren't blank...
[<pre>]function validateFields( oForm ) { //var oForm is the form object for ( var i = 1; i < 7; i ++) { oField = oForm["Quantity" + i]; if ( oField.value.length == 0 ) { alert( 'You need to enter a value field ' + field.name ); return false; } } }[</pre>]
This script compares the length to zero instead of the value to "" because, at least in LotusScript, it's faster that way. I have no idea whether or not it's faster for java-script.
Reply
Thanks it works great
Thanks it I was looking for something like this.. javascript rules...
Reply