Add input value to another value as a total sum - javascript

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

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

Create a totalPrice variable outside of your click function. Then add your addAmount * addPrice to the totalPrice every time you add a new item. Then display the totalPrice in your .totalPrice div instead of the addAmount * addPrice of the last added item.
You may also want to add a call to .toFixed() on your totalPrice when displaying it. Calling totalPrice.toFixed(2) will ensure that you display only two decimal places, so that it's a proper format for monetary values.
Working example:
$(document).ready(function() {
var totalPrice = 0;
$('.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 += addAmount * addPrice;
$(".totalPrice").text("Total Price: $" + totalPrice.toFixed(2));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/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"></div>

Related

User can add new input field with click on button - how to limit/set max fields?

The user can add a new input-field with a click on "Add". My problem is that there is no limit but I want to limit the max. input-fields to 50. Im not that good with js but I think it could done with:
if id or input-field = 50
than disable Add-button. And enable if id or input-field is under 50.
This is my code so far:
function addFormField() {
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}
function removeFormField(id) {
$(id).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Add</p>
<form action="#" method="get" id="form1">
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<p><input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset"></p>
</form>
Thank you
You can set a variable and add 1 to it until the count reaches 50 like this
let currentCount = 0;
function addFormField() {
if(currentCount < 50){
currentCount+= 1;
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}else{
alert('You can not add more then 50')
}
}
function removeFormField(id) {
$(id).remove();
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Add</p>
<form action="#" method="get" id="form1">
<input type="hidden" id="id" value="1">
<div id="divTxt"></div>
<p><input type="submit" value="Submit" name="submit">
<input type="reset" value="Reset" name="reset"></p>
</form>
You have to check for the length of child p tags of your div like this:
if($("#divTxt > p").length) < 50 ){
var id = document.getElementById("id").value;
$("#divTxt").append(
"<p id='row" +
id +
"'><label for='txt" +
id +
"'>Field " +
id +
" <input type='text' size='20' name='txt[]' id='txt" +
id +
"'> &nbsp<a href='#' onClick='removeFormField(\"#row" +
id +
"\"); return false;'>Remove</a><p>"
);
id = id - 1 + 2;
document.getElementById("id").value = id;
}

Javascript function inside HTML document, where am I going wrong?

I'm creating an HTML page for a restaurant bill calculator but i'm having issues with the javascript/input/form and have been stuck for a while. I'm not sure why my function is not working when I submit. If anyone has any ideas where i'm going wrong, I would greatly appreciate any help!
Here is my current code (it has to be in one HTML document):
<body>
<h1>Restaurant Bill Calculator</h1>
<br>
<form name="billcalculator" method=post onsubmit="calculateBill()">
<div class="wrapper">
<label for="tax">Tax Percent:</label>
<input type="number" id="taxPercent" min="0" max="100" step=".01">%
<br>
<label for="price">Price from the menu:</label>
<input type="number" id="menuPrice" min="0" max="1000" step=".01">
<br>
<label for="tip">Tip Percent:</label>
<input type="number" id="tipPercent" min="0" max="200" step=".01">%
<br>
<input type="submit" onclick="calculateBill()" id="submit" value="Calculate Bill">
<br>
</div>
</form>
<p id="display">Please click Calculate Bill after completing form.</p>
<script>
function calculateBill() {
var tax = document.getElementById("taxPercent")
var price = document.getElementById("menuPrice")
var tip = document.getElementById("tipPercent")
var taxamount = price * tax;
var tipamount = price * tip;
var total = taxamount + tipamount + price;
if (!tax.checkValidity()) {
window.alert(tax.validatonMessage);
}
if (!price.checkValidity()). {
window.alert(price.validationMessage);
}
if (!tip.checkValidity()) {
window.alert(tip.validationMessage);
}
if (tax.checkValidity() && price.checkValidity() && tip.checkValidity()) {
document.getElementById("display").innerHTML = "Price: $" + price.toFixed(2) + "\n" + "Tax: $" + taxamount.toFixed(2) + "\n" + "Tip: $" + tip.toFixed(2) + "\n" + "Total: $" + total.toFixed(2);
}
return true;
}
</script>
You need to get and parse the values.
var tax = parseFloat(document.getElementById("taxPercent").value);
var price = parseFloat(document.getElementById("menuPrice").value);
var tip = parseFloat(document.getElementById("tipPercent").value);
Since you have no action in your form, and are not posting anywhere, you can just remove the post method from <form>.
You should also remove the onclick function from your input. There is no reason to have both an onclick and onsubmit handler pointing to the same function.
Then add this to your calculateBill function:
function calculateBill(e) {
e.preventDefault();
Finally, you should be getting the values out of the DOM elements like so:
var tax = document.getElementById("taxPercent").value;
These will be strings, so you will have to use parseInt.

HTML assistance.

I cannot figure out why my to submit button takes me nowhere. I am very new to HTML and programming. Is anyone able to comb through and help me identify why this isn't submitting properly?
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Place an Order - Love that Ink Pen Company</title>
<script>
// values
var name = document.getElementById('cusName').value;
var deliverydate = document.getElementById('delDate').value;
var numItems = parseInt(document.getElementById('numItems').value);
// calculations
var price = numItems * 4.25;
var tax = price * 0.07;
var shipping = price * 0.02;
var totalCost = price + tax + shipping;
// Output text
var text = 'Thank you ' + name + 'for you order.<br/>';
text += 'You will receive ' + numItems + ' items delivered to you on ' + deliveryDate + '.<br/>';
text += 'You price of your items is $' + price.toFixed(2) + '.<br/>';
text += 'The tax charge is $' + tax.toFixed(2) + '.<br/>';
text += 'The shipping charge is $' + shipping.toFixed(2) + '.<br/>';
text += 'Your total is $' + totalCost.toFixed(2) + '.<br\>';;
// Results
document.write('<h2>' + text + '</h2>');;
}
</script>
</head>
<body>
<div style="text-align: left; background-color:Orange; color:Black; 16px;">
<h1>Place an Order</h1>
<form action="#">
<label>Customer Name:</label>
<input type="text" id="cusName"><br>
<label>Delivery Date:</label>
<input type="text" id="delDate"><br>
<label>Number Items:</label>
<input type="text" id="numItems"><br>
</div>
<div style="text-align: left; background-color:Green; color:Black; 16px;">
<input type="submit" id="btnSubmit" value="Submit" onclick="calculateTotal(); return false;" />
</div>
</form>
<div style="background-color:Orange; color:Black; 16px;">
<h2>
Visit our External Website
</h2>
<h2>
Link to our main page.
</h2>
</div>
</body>
</html>
I don't just want an answer, I am looking for what I am doing wrong. I want to learn and understand where I am not comprehending.
First of all you are taking the form to submit the data for your
application there will be no need to form you can do it without form
as well as with form.
second thing is you are calling calculateTotal() function and you
didn't made the function in script tag.
third thing is that deliverydate and deliveryDate are different
thing that you have to change.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Place an Order - Love that Ink Pen Company</title>
<script>
// values
function calculateTotal(){
var name = document.getElementById('cusName').value;
var deliverydate = document.getElementById('delDate').value;
var numItems = parseInt(document.getElementById('numItems').value);
// calculations
var price = numItems * 4.25;
var tax = price * 0.07;
var shipping = price * 0.02;
var totalCost = price + tax + shipping;
// Output text
var text = 'Thank you ' + name + 'for you order.<br/>';
text += 'You will receive ' + numItems + ' items delivered to you on ' + deliverydate + '.<br/>';
text += 'You price of your items is $' + price.toFixed(2) + '.<br/>';
text += 'The tax charge is $' + tax.toFixed(2) + '.<br/>';
text += 'The shipping charge is $' + shipping.toFixed(2) + '.<br/>';
text += 'Your total is $' + totalCost.toFixed(2) + '.<br\>';;
// Results
document.write('<h2>' + text + '</h2>');;
}
</script>
</head>
<body>
<div style="text-align: left; background-color:Orange; color:Black; 16px;">
<h1>Place an Order</h1>
<label>Customer Name:</label>
<input type="text" id="cusName"><br>
<label>Delivery Date:</label>
<input type="text" id="delDate"><br>
<label>Number Items:</label>
<input type="text" id="numItems"><br>
</div>
<div style="text-align: left; background-color:Green; color:Black; 16px;">
<input type="submit" id="btnSubmit" value="Submit" onclick="calculateTotal(); return false;" />
</div>
<div style="background-color:Orange; color:Black; 16px;">
<h2>
Visit our External Website
</h2>
<h2>
Link to our main page.
</h2>
</div>
</body>
</html>
I am looking for what I am doing wrong.
You have defined the script tag in header section ,DOM is not ready when document.getElementById will be executed.Remove them to closing end of body tag
<body>
<!--html-->
<script>
//js code
</script>
</body>
or use windows.load
2.There is no function defined calculateTotal
3.There is an extra colon (:) and } here
document.write('<h2>' + text + '</h2>');;}
4.Typo at deliverydate

JavaScript / JQuery html element append doesn't take attributes of parent - no PHP version

I am using a JQuery after method to append an HTML row to an existing row, but the attributes of the parent are not inherited. What am I doing wrong?
<html>
<head>
<title>AppendTest_min</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
</head>
<body bgcolor="Teal">
<div class="container">
<div class="form-group">
<div class="table-responsive">
<form name="budgetform" id="budgetform">
<table class="table" id="spreadsheet">
<tr id="row1">
<td id="inputtd">
<input type="text" id="descr1" name="descr[]" size="25" class="inputrow" style="font-weight:bold; background-color:Wheat">
<input type="text" id="dueday1" name="dueday[]" style="text-align: center; background-color:Ivory" size="6" class="inputrow">
<button type="button" name="add" id="add1" style="font-weight:bold; background-color:AntiqueWhite; font-size:7px" class="btn_add">+</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.btn_add', function() {
var button_id = $(this).attr("id");
// alert("HELLO");
// alert(button_id);
// get number part of ID
var nLen = button_id.length
var numsize = nLen - 3;
var nIdx = button_id.substr(3, 2);
var sIdx = nIdx.toString();
// alert(sIdx);
var sRowRef = "#row";
var sAddToThisRowRef = sRowRef + sIdx;
nIdx++;
sIdx = nIdx.toString();
var sRemIdx = "rem" + sIdx;
var sAddIdx = "add" + sIdx;
// var sNewRow = '<tr id="row'+nIdx+'"><td><input type="text" id="descr'+nIdx+'" name="descr[]" placeholder="Enter New Description" size = "25" class="inputrow" style="font-weight:bold; background-color:Wheat"/>';
var sNewRow = '<tr id="row' + nIdx + '"><td><input type="text" id="descr' + nIdx + '" name="descr[]" placeholder="Enter New Description" size = "25" class="inputrow" style="font-weight:bold; background-color:Wheat"/>';
sNewRow = sNewRow + '<input type="text" id="duedate' + nIdx + '" name="dueday[]" placeholder="Date Day" size = "6" class="inputrow"; background-color:Ivory" />';
sNewRow = sNewRow + '<button type="button" name="add" id=' + sAddIdx + ' style="font-weight:bold; background-color:AntiqueWhite; font-size:7px" class="btn_add">+</button></tr>';
$(sAddToThisRowRef).after(sNewRow);
// $(sAddToThisRowRef).append(sNewRow);
var sJustAddedRowRef = sRowRef + sIdx;
});
});
</script>
I am not seeing the cellspacing attribute inherited.
This one has had me stumped for a while... Thx!
The behavior you're seeing is because HTML compacts multiple whitespaces into one space character.
Whitespace is present between the <input> and <button> tags in the HTML, so a single space appears between the two input fields and the button in the first row. But no whitespace is present in the HTML constructed in your JavaScript code, so there is no space between those controls in subsequent rows.
The solution is to add a single space ( ) in between the controls as your code constructs them (see lines 2 and 3 below):
var sNewRow = '<tr id="row' + nIdx + '"><td><input type="text" id="descr' + nIdx + '" name="descr[]" placeholder="Enter New Description" size = "25" class="inputrow" style="font-weight:bold; background-color:Wheat"/>';
sNewRow = sNewRow + ' <input type="text" id="duedate' + nIdx + '" name="dueday[]" placeholder="Date Day" size = "6" class="inputrow"; background-color:Ivory" />';
sNewRow = sNewRow + ' <button type="button" name="add" id=' + sAddIdx + ' style="font-weight:bold; background-color:AntiqueWhite; font-size:7px" class="btn_add">+</button></tr>';
Use clone with insertAfter in your scenario. I think its best suited for what your doing.
For Example:
$("#car2").clone().insertAfter("div.car_well:last");
Or you can use try this as well:
$("div[id^='car']:last").after($('#car2').clone());

How to get variable data from prepend/append and do addition with jquery

Hi I am trying to create an invoicing system. I have a form that I add fields to for every line item and that works I can add and remove the form fields. My problem is I dont know a way to get the price from the prepended line item and add it up to get a subtotal.
this is the html nothing interesting here
<div class="form-row">
<strong>Line Items:</strong>
<br>
<div class="line-items">
<div class="line-item">
<div class="line-item-box description">
<label>Description:</label>
<textarea name="description" id="description"></textarea>
</div>
<div class="line-item-box quantity">
<label>Qty:</label>
<input type="text" name="quantity" id="quantity">
</div>
<div class="line-item-box price">
<label>Price:</label>
<input type="text" name="price" id="price">
</div>
<button class="btn add-item">Add Item</button>
</div>
</div>
</div>
Here is the jquery
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="price-row">' + subtotal + '</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
return false;
});
$(document).on('click', '.remove-btn', function() {
$('.line-item').remove();
});
});
So I would like to add up the price var for each line item which will be added to the dom dynamically and then display it with the subtotal var.
Is this possible? If so how can I do this?
For a total use a each loop and sum each parsed value of the price,put this in a function and trigger it each time you update the list of items
js:
function price_subtotal(){
var subtotal = 0;
$('.price-saved').each(function(i,v){
subtotal+= parseFloat($(v).text().replace('$',''));
});
$('.subtotal').html(subtotal);
}
$(document).ready(function() {
$('.add-item').click(function() {
var description = $('#description').val();
var quantity = $('#quantity').val();
var price = $('#price').val();
$('.line-items').prepend('<div class="line-item"><div class="line-item-box description">' + description + '</div><div class="line-item-box quantity">' + quantity + '</div><div class="line-item-box price price-saved">$' + price*quantity + '</div><button class="btn remove-btn">Remove</button></div>');
if (!$('.price-summation')[0]) {
$('.line-items').append('<div class="price-summation"><div class="subtotal price-row">0</div><div class="price-row">Taxes</div><div class="price-row">Total</div></div>');
}
price_subtotal();
return false;
});
$(document).on('click', '.remove-btn', function() {
$(this).closest('.line-item').remove();
price_subtotal();
});
});
DEMO

Categories

Resources