McMaster Posted January 29, 2014 Share Posted January 29, 2014 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 https://forums.phpfreaks.com/topic/285768-js-function-returning-undefined-number/ Share on other sites More sharing options...
.josh Posted January 29, 2014 Share Posted January 29, 2014 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 https://forums.phpfreaks.com/topic/285768-js-function-returning-undefined-number/#findComment-1466957 Share on other sites More sharing options...
McMaster Posted January 29, 2014 Author Share Posted January 29, 2014 Josh! Thank you very much That worked a treat for me. Appreciate that. Link to comment https://forums.phpfreaks.com/topic/285768-js-function-returning-undefined-number/#findComment-1466960 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.