Ad

How Do I Multiply Values From Different Inputs To Get A Total Using Javascript?

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);
}
Ad

Answer

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="">

Ad
source: stackoverflow.com
Ad