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
Related Questions
- → How to update data attribute on Ajax complete
- → October CMS - Radio Button Ajax Click Twice in a Row Causes Content to disappear
- → Octobercms Component Unique id (Twig & Javascript)
- → Passing a JS var from AJAX response to Twig
- → Laravel {!! Form::open() !!} doesn't work within AngularJS
- → DropzoneJS & Laravel - Output form validation errors
- → Import statement and Babel
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
Ad