Get sum of the values from form fields with JS/jQuery - javascript

I have dynamic form like:
<form id="formaa">
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price" onkeyup="update();"></input>
<input type="text" name="sum" id="suma" size="10" disabled="disabled"/>
</div>
<div class="row">
<input type="text" name="item" class="item"></input>
<input type="text" name="quant" class="quant"></input>
<input type="text" name="price" class="price" onkeyup="update();"></input>
<input type="text" name="sum" id="suma" size="10" disabled="disabled"/>
</div>
<!-- ... many more rows -->
<input type="text" disabled id="total" name="tot"></input>
</form>
What I'm trying to do is multiply item quantity and price and get total sum in sum field for each item seperately (not all items total sum).
What I have achiecved is this function, but it seems counting total sum of all items together not seperately and this working with first default field row, when I add new set of fields and fill them with information both, fields (and other later added) sum values become NaN..If I remove all added field sets and leave the first form fows set, number is working again.. What is the problem here?
<script type="text/javascript">
function update() {
var total = 0;
$("#formaa div.row").each(function(i,o){
total += $(o).find(".quant").val() *
$(o).find(".price").val();
if(!isNaN(total) && total.length!=0) {
sum += parseFloat(total);
}
});
$("#formaa div.row #suma").val(total);
}
</script>

function update() {
$("#formaa div.row").each(function(i,o){
var total = $(o).find(".quant").val() * $(o).find(".price").val();
if(!isNaN(total) && total.length!=0) {
sum += parseFloat(total);
}
$(o).find('[name="sum"]').val(total);
});
}
A few problems in your code :
never give the same id to more than one element. That's the reason why I defined the selector on the name
you weren't resetting the total, so it was the sum of all
I didn't fix that, but your operation before the float parsing is strange (it may depend on the content that I can't see)

Related

Multiply input values

Inputs are invisible to jQuery when they are appended.
THere are 3 inputs
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
with this code
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});
If I have these inputs in my html created manually, I can multiply the inputs value and add the result into the total price input.
But I need these inputs to appear after the click event, so I append them. After that they become invisible to jQuery, hence nothing works.
How can I make these inputs appear on the page, in the form, and then manipulate their values?
You did only one mistake while assigning the value to the input field which displays the multiplication result
let $output = $("#output-value");
let $price = $(".bul-order-info__price");
$(document).on('change', ".bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
let tot=value * $price.val();
$(".bul-order-info__total").val(tot);
});
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<input class="bul-order-info__input bul-order-info__price" type="text" name="price" value="500" readonly>
<input class="bul-order-info__input bul-order-info__qnt" type="number" name="quantity" min="1" value="1">
<input class="bul-order-info__input bul-order-info__total" type="text" name="totalPrice" value="" readonly>
</body>
</html>
Jquery can't find dynamically generated elements directly.
You can access them using it's parent which is not appended dynamically.
$(document).on('change', "body .bul-order-info__qnt", function () {
let value = parseFloat($(this).val());
$output.val(value * $price.val());
});

Keeping a running total with Javascript in a span element

I'm trying to write a piece of code that is supposed to keep a running total. More specifically what I would like it to do is, every time you click the button to add the sub total to the total, it should keep adding into the subtotal. The way the whole thing works now is, there is three meal items to choose from in a dropdown that each have their own price. When a food item is selected, the user types in how many of that item they want. Then user clicks the add to total button to add the food item to one text field. Under that field is a span that shows the grand total after a $3.50 delivery charge is added on. The span is where I want the running total to keep adding the sum every time the button is clicked. I am new to Javascript so I've been trying my best. I've also looked at topics here on SO to see if I can find something similar to my issue and I've seen some that are close but not quite what I'm looking for. Here"s my code...
<script>
function myTotal()
{
var meals = document.getElementById("foodItems").value;
var howMany = document.getElementById("itemTotal").value;
var shippingCost = "3.50";
var totalBill = parseFloat(meals) * howMany + parseFloat(shippingCost);
var addingTotal = parseFloat(meals) * howMany;
var runTotal = document.getElementById("runningTotal").value;
if (isNaN(totalBill)) { // Cash calculator
document.getElementById("total").value = "Invalid amount"
//alert("result of isNaN" ); //The input amount is a non numeric string. It is or contains letters and/or spaces
}
else { //adds total to the sub total field
document.getElementById("total").value = "$" + parseFloat(addingTotal).toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
//Convert input value into a floating point number. toFixed() requires a number value to work with
}//end Cash Calculator
var i = ""; //This piece is where I'm trying to begin the running total
if(i=totalBill, i=howMany*totalBill, i++ ){//adds delivery charge + subtotal. But doesn't keep a running total
document.getElementById("runningTotal").innerHTML = parseFloat(totalBill).toFixed(2);
}
else {
document.getElementById("runningTotal").innerHTML = parseFloat(i++) * howMany;
}
}
</script>
<form id="survey" name="survey" method="get" action="formHandler.php" class="col-4">
<!-- enter your forms code below -->
<div id="fieldset">
<legend>Place an Order!</legend>
<h3>There is a $3.50 delivery fee</h3>
<fieldset>
<label for="foodItems">Quick Meal Food Items</label>
<select name="foodItems" id="foodItems">
<option value="6.00">Pepperoni Pizza - $6.00</option>
<option value="3.00">Bacon BBQ Burger - $3.00</option>
<option value="8.00">Steak and Eggs - $8.00</option>
</fieldset>
<!--The "input" element has "required" in the parameters so the user must fill out all fields but the email.-->
<fieldset>
<input type="text" name="itemTotal" id="itemTotal" size="25" required>How Many Orders?(Limit To 5 per Meal Type)</input>
</fieldset>
<fieldset>
<input type="button" name="click" id="button" value="Add to Order" onClick="myTotal()">
<input type="text" name="total" id="total" size="25">Grand Total</input>
<br>
<span id="runningTotal"></span> <!--runningTotal span-->
</fieldset>
<label for="name">Name: (First, Last)</label>
<input type="text" name="name" id="name" size="25" required></input>
<label for="Address">Address</label>
<input type="text" name="Address" id="address" size="25" required></input>
<label for="email">Email</label>
<input type="email" name="email" id="email" size="40" maxlength="40"></input>
<br><br>
<label for="checkbox">Sign me up for deals via email</label>
<input type="checkbox" name="checkbox" id="checkbox" value="Signup" checked="checked"></input>
<input type="submit" method="post" value="Submit" class="button"/>
<input type="reset" value="Reset" class="button"/>
</form>
</div>
Any help would be awesome! Please address any confusion please. I want to be as clear as possible to try to get the best help for me and others here on SO. I also hope my question isn't off topic. Like I said, I tried to find something pertaining to this here on SO. Thank you so much!
Do you mean something like this? (jsfiddle here)
function myTotal()
{
// Error checking removed....
// Calculate cost of current item
var itemSelect = document.getElementById("foodItems");
var mealCost = parseFloat(itemSelect.value);
var howMany = parseInt(document.getElementById("itemTotal").value);
var thisItemCost = mealCost * howMany;
var shippingCost = 3.5;
// Get running total from the "total" text box
var runTotal = parseFloat(document.getElementById("total").value);
// Only add shipping cost once
if (isNaN(runTotal) || 0 == runTotal) runTotal = shippingCost;
// Add this item to total and update "total" text box
document.getElementById("total").value = (thisItemCost + runTotal).toFixed(2);
// Add item to span
document.getElementById("runningTotal").innerHTML += "</br>" +
itemSelect.options[itemSelect.selectedIndex].innerHTML +
" x " + howMany +
" .... $" + thisItemCost.toFixed(2);
}

Calculate Arrays with input field instead of span or div

I'm trying to do a simple calculation onblur with arrays but it's not firing. If I change it to a span or div it works fine. Why isn't it working with an input field?
I need it to be an input field because it's easier to store the values in a database.
<input type="text" class="input-small" name="partnumber[]">
<input type="text" class="input-small" name="partdescription[]" >
<input type="text" class="input-small" name="partprice[]" onblur="doCalc(); calculate(); ">
<input type="text" class="input-small" name="partquantity[]" onblur="doCalc(); calculate(); ">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
Calculation
function doCalc() {
var total = 0;
$('tr').each(function() {
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
});
$('.parttotal').each(function() {
total += parseInt($(this).text(),10);
});
}
Firstly, I wouldn't use inline events.. Here I've used delegated events, an advantage here if you dynamically add any more lines, it will still work..
Next make sure each line has some sort of wrapper for each line, here I've used a simple DIV. Yousr might be your TR..
The rest then becomes easy, as can be seen here, this example I've just included the price, qty & total, and done 2 lines for testing..
function calc() {
var h = $(this).closest('div');
var qty = h.find('[name="partquantity[]"]');
var price = h.find('[name="partprice[]"]');
var total = h.find('[name="parttotal[]"]');
total.val(qty.val() * price.val());
}
$('body').on('blur', '[name="partprice[]"],[name="partquantity[]"]', calc);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
<div>
<input type="text" class="input-small" name="partprice[]">
<input type="text" class="input-small" name="partquantity[]">
<input type="text" readonly class="input-small parttotal" name="parttotal[]" >
</div>
you can't use .html() to set the value of a textbox.
Change this line:
$(this).find('.parttotal').html($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
to
$(this).find('.parttotal').val($('input:eq(2)', this).val() * $('input:eq(3)', this).val());
Note the change ('.parttotal').html becomes ('.parttotal').val

Calculating sum of input type generated using AJAX

I have these input fields with same id, name. These inputs are generated using the ajax code as per the user choices. I want to do the sum of theses input fields(p_amount) in total_amount field using jquery.
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="p_amount" name="p_amount[]" placeholder="Enter Amount ">
<input type="text" id="total_amount" name="total_amount" value="" placeholder="Total Amount">
I am using following js code but it only return the sum of digits entered in first text field. and i want sum of all the id's with p_amount. Please help me here.
<script type="text/javascript">
$('#total_amount').click(function() {
var p_amount=$("#p_amount").val();
var total = 0;
for (var i = 0; i < p_amount.length; i++) {
total += p_amount[i] << 0;
}
</script>
Try this,
var total=0;
$('#total_amount').click(function() {
$("input[name='p_amount[]'").each(function(){
total+=parseInt($(this).val());
});
});
alert(total);
The problem is that the ids of the fields you use must be distinct. You should use class attributes for annotating multiple elements.
Then you can get these with JQuery and iterate through them with .each().
You can find more information and examples here:
JQuery .each()

Array textboxes with onchange event

<INPUT name="Qty[]" id="Qty[]" type="text" class="south" />
<INPUT name="Amount[]" id="Amount[]" type="text" class="south"/>
<INPUT name="TotalAmount[]" id="TotalAmount[]" type="text" class="south" disabled="disabled"/>
Here i have problem with my code that i need to calculate multiply the first two textboxes. and that result will be appear into the last one, i mean third textbox as TotalAmount. Could you help me? here three textboxes appeared in single row with add button. when i submit the add button new created with three boxes again. I need to finish it in jquery of java script. please help me guys
First of all, remove the array-declaration, you're not using the the input fields as arrays. they are single values.
<INPUT name="Qty" id="Qty" type="text" class="south" />
<INPUT name="Amount" id="Amount" type="text" class="south"/>
<INPUT name="TotalAmount" id="TotalAmount" type="text" class="south" disabled="disabled"/>
And the jquery.
$(document).ready(function(){
qty = $("#Qty").val();
amount = $("Amount").val();
$("#Qty, #Amount").keyup(function(){
$("#TotalAmount").val((qty)*(amount));
});
});
Here is your JavaScript:
$(document).ready(function () {
var $quantity = $('#Qty\\[\\]'),
$amount = $('#Amount\\[\\]'),
$total = $('#TotalAmount\\[\\]'),
quantity,
amount;
$($quantity.add($amount)).keyup(function () {
quantity = Number($quantity.val().replace(/[^0-9,.]/g, ''));
amount = Number($amount.val().replace(/[^0-9,.]/g, ''));
$total.val(quantity * amount);
});
});
UPDATE Changed to keep the DOM ids the same in case they have to be that way. For an unmentioned reason as mentioned by #Ken Keenan.

Categories