...

View Full Version : Check for the existence of a variable with a calculated name?



briandunning
01-29-2009, 02:00 AM
Hi, I'm processing a form with numbered fields, but I don't know how many fields there are. Might be 1, might be 20. So I'm iterating through 1-20 and trying the following test:

for(i=1; i<=20; i++) {
if(typeof(eval('document.edit_orderitem_form.field_'+i+'.value')) != 'undefined') {
[doing stuff with the form field here]
}
}

The script quits on that line with "Undefined value" showing up in Safari's error console. I just can't figure out how to eval() the name of a field when it may or may not exist, and have the script continue gracefully. Thanks.

rangana
01-29-2009, 03:44 AM
No need for eval() here. Try to replace this part:


for(i=1; i<=20; i++) {
if(typeof(eval('document.edit_orderitem_form.field_'+i+'.value')) != 'undefined') {



...with:


for(var i=1; i<=20; i++) {
if(typeof document.edit_orderitem_form.elements['field_'+i] != 'undefined'){


P.S., I haven't tested it at my end, but hopefully, should work.

Hope that helps.

briandunning
01-29-2009, 04:13 AM
Interesting. I will try it, but there is one more complication: For clarity, I left one more variable out of my example code. There are multiple forms on the page, so there is also a variable ii that tells what form to use. Is it possible to use the elements[] twice, once for the form name, and once for the field name?

rangana
01-29-2009, 04:33 AM
If you want to loop through all of the forms, you can use form (forms[]) collection instead of the elements[].

For further reading:
http://www.w3schools.com/htmldom/coll_doc_forms.asp

Hope that helps.

briandunning
01-29-2009, 07:19 PM
I'm not looping through forms, I'm only receiving input from one of them. So what I need to get is this:


document.form_XXX.field_YYY.value
where XXX is a value passed to my script, and YYY is determined by looping and iterating. The first few YYYs will exist, but not all of them.

Can I say something like this?:


formname = 'form_' + XXX;
for(i=1; i<=20; i++) {
if(typeof document.form[formname].elements['field_'+i] != 'undefined'){
[doing stuff with the form field here]
}
}

Whew... :-)

briandunning
01-29-2009, 08:35 PM
I got it figured out. The solution was to not use eval() at all, and use try{} instead of checking for undefined. Thanks.

for(i=1; i<=20; i++) {
try {
[do stuff with:] document.forms['form_'+xxx].elements['field_'+i].value;
}
catch(err) {
// Do nothing
}
}



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum