Page 1 of 1

Javascript for loop involving fieldname[i]'s

Posted: Wed Nov 22, 2006 6:27 am
by will83
I am buildign a form validation script which will loop through certain fieldnames. These fieldnames are the same apart from they are numbered i.e.

tenanttype1
tenanttype2
tenanttype3

Where in php we can do something like:

Code: Select all

echo "if (document.form1.tenanttype".$count.".value == 'students'";
I am looking to find out what the correct punctuation as it were in jscript that would perform the same concept, allowing me to insert the variable 'count'. So I have the following as an example:

Code: Select all

var count = 1 
var p = 10

for (i=0;i<=p;i++) {
	if (document.form1.tenanttype[count].value == 'professional' || document.form1.tenanttype[n].value == 'students') {
		document.getElementById('contsum1').value = '';
		document.getElementById('contsumrow1').style.display = '';
                                count++;
}
Any help appreciated,

Thanks, Will

Posted: Wed Nov 22, 2006 6:30 am
by feyd
Moved to Client Side.

document.forms['formName'].elements['elementName'].value

Posted: Wed Nov 22, 2006 6:36 am
by will83
Thanks but it hasn't really helped. What method do I use to insert the auto incremented variable of 'count' into that line?

Posted: Wed Nov 22, 2006 7:19 am
by HCBen
The variable you set in your forloop is your counter, in this case it's "i", so:

Code: Select all

for (var i=0; i<=p; i++)
{
     if (document.form1.tennattype[i].value == 'professional') etc....
}

Posted: Wed Nov 22, 2006 8:02 am
by will83
HCBen,

I believe I use your method if I am looping through and calling values from an array.

However tenanttype is not an array but a single value. Fields on the page are tenanttype1, tenanttype2, tenanttype3....

Posted: Wed Nov 22, 2006 9:46 am
by choppsta
As Feyd said:

Code: Select all

for (i=0;i<=p;i++) {
        value = document.forms['formName'].elements['tenanttype'+i].value;
}

Posted: Wed Nov 22, 2006 10:49 am
by will83
Thanks. Fetd omitted the ....'tenanttype'+i].....

Quite important don't you think.

Posted: Wed Nov 22, 2006 2:04 pm
by feyd
There shouldn't have been a need to add the "dynamic" part.. but I guess there was. :roll: