0

I am trying to do a shopping cart where I want the total to automatically change after the quantity is inputted (the total is the price times the quantity). I'm trying to use Javascript for this and I just can't seem to get it as it is coming up with null and before it said NaN.

PS: It is a console log at the moment just to see if it works, but I will need it to go into the total input tag.

HTML:

<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="$18.95">

JavaScript:

function calcTotal() {
  var price = document.getElementById("price").value;
  var quantity = document.getElementById("quantity").value;
  var total = price * quantity;
  console.log(total);
}
b07580
  • 41
  • 7
  • 2
    What do you expect for `"$18.95" * "1"`? You should be multiplying numbers, not String. – Rayon Jun 08 '20 at 07:56

2 Answers2

1

Try this:

function calcTotal() {
// remove $ sign and parse Float price
  var price = parseFloat(document.getElementById("price").value.substr(1));
 // parse float quantity
  var quantity = parseFloat(document.getElementById("quantity").value);
  var total = price * quantity;
  //pass calculated value to input with id total
  document.getElementById("total").value = "$" + total;
}
<input id="price" type="text" readonly value="$18.95">
<input id="quantity" type="text" value="1" onchange="calcTotal()">
<input id="total" type="text" readonly value="">
Flori Bruci
  • 436
  • 4
  • 11
1

Any operation that involves a string returns NaN, however you should coerce your input values as Number

function calcTotal() {
  var price = document.getElementById("price").value;
  var quantity = document.getElementById("quantity").value;
  var total =Number(price) * Number(quantity);
  console.log(total);
}

Using Number vs parseFloat

So as long as you have standard numeric input, there's no difference. However, if your input starts with a number and then contains other characters, parseFloat truncates the number out of the string, while Number gives NaN (not a number):

parseFloat('1x'); // => 1
Number('1x'); // => NaN
IAMSTR
  • 618
  • 8
  • 12