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 Wanet Telecoms Ltd on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Issue with a for statement

Status
Not open for further replies.

Julian4145

Programmer
Oct 28, 2003
27
US
Can anyone tell me why this code loops through 16 times instead of 8?

var TotalAmount = 0;
var tmpAmount;

for (i = 0; i <= 8; i++){
tmpAmount = parseFloat(form.elements('txtAmount' + i);
if (tmpAmount != 'NaN'){
TotalAmount = TotalAmount + tmpAmount;
alert('TotalAmount');
}
}

I'm trying to test to see if there is a number in a field (txtAmount + i) thats in another loop that runs 8 times. If there is a number, I want to add it to the total. In the testing I was doing there is 400 in txtAmount1 and 50 in txtAmount2 and the other 6 are blank. Eventually, what I am trying to do is to check to see if the total of the txtAmount fields is < 500 and if so to return false. When the code runs, I get an alert box that reads 400 followed by 450, then 6 boxes that read NaN. The alert boxes then repeat themselves a second time.
 
form.elements('txtAmount' + i);

should be

form.elements['txtAmount' + i];

=========================================================
-jeff
try { succeed(); } catch(E) { tryAgain(); }
 
I tried that. Its still running through the for statement twice. I'm not sure whats going on here. Anyone?

Julian
 
The loop will be executed 9 times for [tt]i = 0, 1, 2, 3, 4, 5, 6, 7, 8[/tt] because of the [tt]<=[/tt]. If you want it [tt]8[/tt] times:
Code:
   for (i = 0; (i < 8); ++i) {
      // added misding ')' in you code and corrected for []
      tmpAmount = parseFloat(form.elements['txtAmount' + i]);
      // I prefer isNaN() to your comparison
      if (!isNaN(tmpAmount)) {
         TotalAmount = TotalAmount + tmpAmount;
         alert('TotalAmount');
      }
   }
Hope this helps

________________________________________
[hippy]Roger J Coult; Grimsby, UK
In the game of life the dice have an odd number of sides.
 
Thanks! That i=0 was a typo, I had 1 in the actual code. I was trying to recreate the code from my memory.

Julian
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top