Naomi Naomi - 1 year ago 64
Javascript Question

Add input value to another value as a total sum

I'm creating a budget app where the user can put in a product and a price. I want it to display the total cost by adding each input value (HTML5 type=number) to the next number that is put in with the next added line.


$(document).ready(function() {

$('.food').click(function() {
var $frm = $(this).parent();
var toAdd = $frm.children(".productInput").val();
var addPrice = $frm.children(".priceInput").val();
var addAmount = $frm.children(".amountInput").val();

var div = $("<div>");
div.append("<p>" + addAmount + "</p>", "<p id='product'> " + toAdd + " </p>", "<p>" + addPrice + "</p>");


$(".totalPrice").text("Total Price" + addAmount * addPrice);


<script src=""></script>
<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<input class='amountInput' type='number' name='quantity' min='0' max='1000' step='1'>
<input class='productInput' type="text" name="message" value="">
<input class='priceInput' type='number' name='quantity' min='0' max='1000000' step='0.01'>
<button class="food">Add</button>
<div class="messages">
<div class="totalPrice">

How can I do this? :)


Answer Source

Declare a global variable outside your function

$(document).ready(function() {

var totalPrice=0;

$('.food').click(function() {

do this while calculating total price

totalPrice = totalPrice + (addAmount * addPrice);
$(".totalPrice").text("Total Price" + totalPrice);