Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations derfloh on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Print value of entries using for loop 2

Status
Not open for further replies.

evergreean

Technical User
Joined
Feb 15, 2006
Messages
68
Location
US
How do I get the values entered to print out in my alert using a for loop?
Currently it goes through the for loop and prints the literal values. The below will print 3 literals with each fieldname only but not the values:

Code:
<script>
function myT()
{
for(var i=1;i<4;i++)
{
   alert("document.tes.firstname"+[i]+".value");
   //The below alert wont alert anything
   //alert(document.tes.firstname[i].value);
}

}

</script>
<form name="tes" method="post" action="actionPage.cfm" onsubmit="return myT();">
<input type="Text" name="firstname1">
<input type="Text" name="firstname2">
<input type="Text" name="firstname3">
<input type="Submit" value="submit">
</form>
The script Pops up 3 alerts with literal field names:
document.tes.firstname1.value
document.tes.firstname2.value
document.tes.firstname3.value

I want it to pop up 3 alerts with each value entered.
 
You should use the forms and elements collections. That will solve your problems.
Code:
function myT() {
   for(var i = 1; i < 4; i++) {
      alert(document.[!]forms["tes"].elements["firstname" + i][/!].value);
   }
}

-kaht

<P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <B> <P> <.</B>
 
Or to get all the values at once store them into a variable and then output at the end instead of having a bunch of popups.
Here is an example using a modified version of kaht's code above:
Code:
function myT() {
  var outstr='';
  for(var i = 1; i < 4; i++) {
    outstr = outstr + document.forms["tes"].elements["firstname" + i].value + '\r\n';
  }
  alert(outstr);
}

Stamp out, eliminate and abolish redundancy!
 
Thanks for the very quick responses and answers!
It now works.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top