CK
2011-03-26 19:49:27 UTC
I have a form, that using Javascript, will automatically update the price in the textbox if the user selects one of the checkboxes/radio buttons. However, I keep getting the NaN error, and cant figure out whats wrong.
This is my function in javascript:
function updateTotal() {
var productGroup = document.getElementsByName('product');
var i = productGroup.length;
var sum = 0;
var deliveryGroup =document.getElementsByName
('deliveryType');
var c = deliveryGroup.length;
var delivery = 0;
var total = document.getElementById('total')
while(i--) {
if(productGroup[i].checked){
sum += parseFloat(productGroup[i].value);
}
}
if(sum > 0){
while(c--){
if(deliveryGroup[c].checked){
delivery = parseFloat(deliveryGroup[c].value);
}
}
total.value = (sum + delivery).toFixed(2);
}
else{
total.value = sum;
}
}
And here is my HTML code for the checkboxes/radio buttons:
622 Standard Fit Trainer
Biker - Flower Girl
h3>Nike Flytop Mens Trainers
ANY help on this would be greatly appreciated !!
Four answers:
?
2011-03-27 04:55:07 UTC
Also, if parseFloat() doesn't change a string to a number then why is it that you can do addition with the values it returns? If it keeps them as strings wouldn't it concatenate instead?
W3C schools has this to say about parseFloat():
"The parseFloat() function parses a string and returns a floating point number."
So they seem to disagree with Craig.
fantabulum
2011-03-26 20:19:16 UTC
Edit
=======
NaN does mean Not a Number and DOM is document object module (that is the way JavaScript and HTML reference object on a 'canvass' to reference elements). For instance if I give you a string (a word) that is "16", JavaScript cannot add a number to that as a calculator would; because that is a string (i.e. word). Therefor if I added the sting "1" to the word "16" I would have "161"; the same way if I added "b" to "aa" I would get "aab". First I must convert the string "16" to the number 16 before I can perform mathematical functions to it; therefor the string "16" is Not a Number. I'll read your specific code when I'm a bit more sober but I hope this helps.
Craig
2011-03-27 04:09:02 UTC
delivery = parseFloat(deliveryGroup[c].value);
Doing this will cause a 'NaN' return as you're trying to parse "home" (for example) as a Float (which is a numeric datatype. So you will need to look at your control's value as title and value seem to be the wrong way round. Rather than title="3.99" try it's value property. It probably wont fix the issue, but it'll be somewhere to start.
Also, parseFloat() wont convert a string to a numeric value, it'll simply read the value to see if it is a float. Try converting it to a number using Javascript's Number() method.
Take a look at:
http://www.w3schools.com/js/default.asp
Great resource to start! Good luck.
2016-10-03 12:16:12 UTC
ⓘ
This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.