Naomi Naomi - 7 months ago 20
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.

Snippet:



$(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>");

$frm.parent().children(".messages").append(div);

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

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="menu">
<h3>Shopping list</h3>
<div class="line">
<div>
<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>
<div class="messages">
</div>
</div>
</div>
<div class="totalPrice">





How can I do this? :)

Thanks

Answer

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);
Comments