Javascript for loop involving fieldname[i]'s

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
will83
Forum Commoner
Posts: 53
Joined: Thu Nov 10, 2005 3:13 pm

Javascript for loop involving fieldname[i]'s

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

Moved to Client Side.

document.forms['formName'].elements['elementName'].value
User avatar
will83
Forum Commoner
Posts: 53
Joined: Thu Nov 10, 2005 3:13 pm

Post 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?
User avatar
HCBen
Forum Commoner
Posts: 33
Joined: Thu Jun 22, 2006 3:15 pm
Location: Indiana

Post 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....
}
User avatar
will83
Forum Commoner
Posts: 53
Joined: Thu Nov 10, 2005 3:13 pm

Post 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....
choppsta
Forum Contributor
Posts: 114
Joined: Thu Jul 03, 2003 11:11 am

Post by choppsta »

As Feyd said:

Code: Select all

for (i=0;i<=p;i++) {
        value = document.forms['formName'].elements['tenanttype'+i].value;
}
User avatar
will83
Forum Commoner
Posts: 53
Joined: Thu Nov 10, 2005 3:13 pm

Post by will83 »

Thanks. Fetd omitted the ....'tenanttype'+i].....

Quite important don't you think.
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

There shouldn't have been a need to add the "dynamic" part.. but I guess there was. :roll:
Post Reply