Jump to content

JS Function Returning undefined number


McMaster
Go to solution Solved by McMaster,

Recommended Posts

Hi!

 

I have a javascript function that loops through certain elements on a page and add's the elements up.

 

For example, element 1 value is 20 and element 2 value is 10. The alert in the loop should be showing 20 and then 10, but it just shows undefined20.00 and the stops?

 

Here is my function...

		function updatePrice(couponPrice,couponQuanity,whichPrice,howMany) {
			var price = couponPrice * couponQuanity;
			var x;
			var ptotal;

			var myItems = new Array();

			document.getElementById(whichPrice).innerHTML=price.toFixed(2);

			for (x=1;x<howMany+1;x++) { 
				myItems[x] = document.getElementById('totalPrice' + x).innerHTML;

				ptotal+=myItems[x];
				alert(ptotal);

			}


		}
Link to comment
Share on other sites

So one thing I see wrong is you have this:

 

var ptotal;

// stuff

myItems[x] = document.getElementById('totalPrice' + x).innerHTML;
ptotal+=myItems[x];
Okay so first you declare ptotal but don't assign anything to it, so even though it's declared, it's undefined. then you attempt to add add myItems[x] to it, which is a string type value, because .innerHTML is a string type value. So javascript stringifies the typeof ptotal (which is 'undefined') and uses the + operator in the context of string concatenation to concatenate the string value of what's in that element's innerHTML.

 

To fix this, you need to initialize ptotal as a number type, by assigning a value to it:

 

var ptotal=0;
Then, you need to convert the value of myItems[x] to a number type, before adding it to ptotal:

 

myItems[x] = document.getElementById('totalPrice' + x).innerHTML;
ptotal+=Number(myItems[x]);
Beyond that, since you are saying you are only getting an alert of "undefined20.00", to me that means that you have a mis-alignment of your html element id names vs. array index vs. that howMany value. Which means basically your loop isn't looping through all of your html elements. I can't really confirm this without seeing more code, like your actual html elements and what value howMany actually is, etc..
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.