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.

 

 

 

 

 

 

Link to comment
Share on other sites

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.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.