1

The alert you see after the while loop keeps saying NaN for the price variable. Idk what's wrong with my code but I know it has to do with the value attributes/parsing ints. Everything else works fine Can anyone spot it? Thank you!

var c = 0;
while (checkedBoxes[c] != null) {
    price += parseFloat(checkedBoxes[c].value);
    c++;
}
alert("You picked " + c + " ingredients. That will cost you " + price + " dollars.");

Here is the html I have that i refers to:

<li name="meatItem" id="m1">
    <input type="checkbox" name="checkItem" id="Pep" value="1.5">Pepperoni
</li>
<li name="meatItem" id="m2">
    <input type="checkbox" name="checkItem" id="CB" value="1.5">Canadian Bacon
</li>
putvande
  • 15,068
  • 3
  • 34
  • 50
gcc
  • 283
  • 1
  • 3
  • 14
  • 2
    Please show how `checkedBoxes` and `price` are declared. – MasterAM Sep 13 '13 at 20:16
  • Yep, I had to set price = 0 to start with. Wow, dumb mistake. THANK YOU! And yes, I just left all of the other code out, such as the check boxes but I have it all there – gcc Sep 13 '13 at 20:20
  • Cool. BTW, if you want to sum up only the checked values, your function does not do that. And a `for` loop will probably serve you better. – MasterAM Sep 13 '13 at 20:26
  • You might want to check this: [Is JavaScript's Floating-Point Math Broken?](http://stackoverflow.com/questions/588004/is-javascripts-floating-point-math-broken) – Jonathan Sep 13 '13 at 20:50
  • @Jonathan, yeah, you have a point. As long as he uses floats that can be represented as finite binary fractions, he's good to go. This goes for 1, 1.5, 1.75 etc. The OP is actually better off having the price represented as cents at first, formatting the displayed value as `Math.floor(c/100) + '.' + c%100` or the like. – MasterAM Sep 13 '13 at 21:30

0 Answers0