Jump to content

Problem adding values from a form input in a for loop


tendrousbeastie

Recommended Posts

Hi All,

 

 

I'm pretty new to JS and could do with some help. I'm used to PHP see, and I think there is probably a fundamental difference in how the two languages operate to do with objects and functions that is throwing me.

 

Specifically, I have a set of inputs (type=text) on my form with names 'lang_cost_conv_1', 'lang_cost_conv_2',.etc.

 

As there are an unknown number of these input on any given page (as the page is dynamically generated from PHP) I have had to construct a for loop in javascript to reference these inputs.

 

 

var totalCost = 0;
var temp; 

for ( var n	= 0; n <= total; n++)
{

temp		=	parseFloat(document.quote[element].value);
alert(n+' = '+temp);
totalCost	=	totalCost + temp;

}

alert (totalCost+" :::: "+total);

return true;			

 

 

Note: $total in the above is passed as an arguement to the function, and I am happy that it is fine. The parseFloat doesn't make a difference (i.e. the error still occurs if I remove it.).

 

Now, in the above code, the alert box is displaying correctly (i.e. it is showing exactly the correct value of the relevant input box.

 

But I get an error with the line below it, where I try to add temp to totalCost. In FF it errors with = has no properties. In ie is errors saying is null or is an object.

 

So, it looks like temp is referencing the object for the input box, rather than grabbing its value. Is this correct? If so, how should I re-write this so that temp contains the numeric value of the box, rather than a reference to it?

 

I hope I've been clear enough. Thanks for any help.

 

 

 

 

 

 

I'm sorry, I forgot to point out that the error message says the problem is on the line:

 

temp		=	parseFloat(document.quote[element].value);

 

 

Although I can't see how, if the alert box in the line after is working.

 

I have also tried it with putting a second alert immediately after the first containing alert(typeof temp), and it shows 'number' as a result.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.