Multiply and sum input values created dynamically in Jquery
You need to calculate the sum according to each value and not add every time the new value.
So what I did :
I added a class ".sum" to each result input (to select them)
I made 2 functions : one to calculate the result of the row + one for the sum
I added the new function on keyup event
So the logic is, when you change an input value :
- the result of the row change (as before)
- you calculate the sum according to each result input, starting at 0 (new)
<div class="inputs"></div><button type="button" id="new">NEW</button><br><br>Total:<input id="total" type="text" readonly> <script src="https://code.jquery.com/jquery-1.12.0.min.js"></script> <script> $("#new").click(function(){ var cont = $(".numb").length; var index = cont + 1; var add = "<div><input class='numb' id='nn_"+index+"' onkeyup='calculate("+index+"); total()'> X <input id='mm_"+index+"' onkeyup='calculate("+index+"); total()'> = <input class='sum' id='result_"+index+"' readonly></div>"; $(".inputs").append(add); }); function calculate(idx){ $("#result_" + idx).val($("#nn_" + idx).val() * $("#mm_" + idx).val()); } function total() { var sum = 0; $.each($(".sum"), function() { sum = sum + Number($(this).val()); }); $("#total").val(sum); } </script>
jQuery Sum or Multiply values always without event trigger
Rather than continuing in comments, I thought an answer might be of better use. Currently, you use:
$(".form-control).change(...)
to trigger the update. Some browsers may force you to lose the focus on an element to actually trigger that. Instead, change that line to:
$(".form-control").on("input", function(){ ... })
This has been discussed here: What is the difference between "change" and "input" event for an INPUT element
Other than that, I've made no changes to your fiddle: https://jsfiddle.net/snowMonkey/kpLs9zcg/5/
jQuery sum multiples input fields (price * quantity) dynamically added with same class
Ok, this is how i figured out googoling and searching on other post on this site JSFIDDLE IS HERE, hope can help someone else:
<div class="page">
<ul>
<li>Quantità: <span><input type="text" name="Quantita" value="" class="quantita"></span></li>
<li>Valore unitario: <span><input type="text" name="ValoreUnitario" value="" class="valore"></span></li>
<li> Valore totale: <span><input type="text" name="ValoreTotale" value="0.00" class="somma"></span></li>
</ul>
<div id="foo"></div>
<input type="submit" value="ADD MORE" class="button" id="clicca">
<ul>
<li>Total amount:<input id="amount" type="text" name="Imponibile-Importo" value="0.00"></li>
</ul>
</div>
and the script here:
$(".page").on("change keyup keydown paste propertychange bind mouseover", function(){
calculateSum();
});
// add fields
$( "#clicca" ).click(function() {
$( "#foo" ).append(
'<ul>' + '\n\r' +
'<li>Quantità: <span><input type="text" name="Quantita" value="" class="quantita"></span></li>' + '\n\r' +
'<li>Valore unitario: <span><input type="text" name="ValoreUnitario" value="" class="valore"></span></li>' + '\n\r' +
'<li>Valore totale: <span><input type="text" name="ValoreTotale" value="0.00" class="somma"></span></li>' + '\n\r' +
'</ul>'
);
$(".somma").each(function() {
$(this).keyup(function(){
calculateSum();
});
});
});
// function
function calculateSum() {
var sum = 0;
$(".somma").each(function() {
if(!isNaN(this.value) && this.value.length!=0) {
var quantita = $(this).closest("ul").find("input.quantita:text").val();
var valore = $(this).closest("ul").find("input.valore:text").val();
var subTot = (quantita * valore);
$(this).val(subTot.toFixed(2));
sum += parseFloat(subTot.toFixed(2));
}
});
$('#amount').val(sum.toFixed(2));
}
jquery to sum two inputs on dynamic table and display in third
You're only giving the elements a name attribute, but using the id selector ([id^=price]). It's much easier to give them a specific class than having to use that "id starts with" selector. Also, when do you want the line totals to be calculated? And when do you want the grand total to be calculated? On what event(s)?
Here's my interpretation of how it should look:
<table class="order-list">
<thead>
<tr><td>Product</td><td>Price</td><td>Qty</td><td>Total</td></tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="product" /></td>
<td>$<input type="text" name="price" /></td>
<td><input type="text" name="qty" /></td>
<td>$<input type="text" name="linetotal" readonly="readonly" /></td>
<td><a class="deleteRow"> x </a></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="5" style="text-align: center;">
<input type="button" id="addrow" value="Add Product" />
</td>
</tr>
<tr>
<td colspan="5">
Grand Total: $<span id="grandtotal"></span>
</td>
</tr>
</tfoot>
</table>
And the JS:
$(document).ready(function () {
var counter = 1;
$("#addrow").on("click", function () {
counter++;
var newRow = $("<tr>");
var cols = "";
cols += '<td><input type="text" name="product' + counter + '"/></td>';
cols += '<td>$<input type="text" name="price' + counter + '"/></td>';
cols += '<td><input type="text" name="qty' + counter + '"/></td>';
cols += '<td>$<input type="text" name="linetotal' + counter + '" readonly="readonly"/></td>';
cols += '<td><a class="deleteRow"> x </a></td>';
newRow.append(cols);
$("table.order-list").append(newRow);
});
$("table.order-list").on("change", 'input[name^="price"], input[name^="qty"]', function (event) {
calculateRow($(this).closest("tr"));
calculateGrandTotal();
});
$("table.order-list").on("click", "a.deleteRow", function (event) {
$(this).closest("tr").remove();
calculateGrandTotal();
});
});
function calculateRow(row) {
var price = +row.find('input[name^="price"]').val();
var qty = +row.find('input[name^="qty"]').val();
row.find('input[name^="linetotal"]').val((price * qty).toFixed(2));
}
function calculateGrandTotal() {
var grandTotal = 0;
$("table.order-list").find('input[name^="linetotal"]').each(function () {
grandTotal += +$(this).val();
});
$("#grandtotal").text(grandTotal.toFixed(2));
}
http://jsfiddle.net/QAa35/
In your JS, you weren't using linetotal
for the one dynamic input's name
. There were other several minor modifications I made. You might as well use <thead>
, <tbody>
and <tfoot>
since you do have those sections in the <table>
. Also, I don't think it's a good design to have a new row automatically added when the "product" inputs are changed. That can happen often, and their intent may not be to add a new product...a button is much more friendly. For example, say you type in "asdf" to the first "product" input, then click somewhere. A new row is added. Say you made a typo so you go back and change it to "asd", then click somewhere. Another new row is added. That doesn't seem right.
Multiply input values into span
From the OP it is understand that .result
is a span
so $("input").next(".result").val(sum);
won't work because span
does not have a function called .val()
use .text()
instead. And also change
var rank = $("input").next(".rank").val();
to
var rank = $(this).next(".rank").val();
DEMO HERE
EDIT
Based on OP's comment. try this
$(document).on("change", ".parent", function() {
var sum = 0;
$(".parent").each(function() {
var rank = $(this).next(".rank").val();
sum = $(this).val() * rank;
$(this).parent().find(".result").text(sum);
});
});
UPDATED DEMO
how do I sum some input fields value (plus multiply is value by an attribute representing price)
Your question is a little confusing without html, but I think you want to multiply each item in the loop by it's price, which is stored in a data-*
attribute. So change this line:
sum += parseFloat(this.value);
to this:
sum += parseFloat(this.value * $(this).data('price'));
some additional parsing may be neccessary without knowing your code too well:
sum += parseFloat(this.value) * parseFloat($(this).data('price'));
FYI:
.data('price')
will get you the attribute named data-price
on a jQuery object.
Related Topics
How to Increment a Number After Every 1 Second Using JavaScript
How Does Group by Works in Sequelize
How to Put a Variable in an Src Attribute
How to Refresh an Angular Component
Javascript Loop Wait Until API Call Finished
How to Make Mongoose Not Insert Empty Array or Object Fields into a Document
Google Charts - Labels Are Not Showing
Regex to Replace Multiple Spaces With a Single Space
Angular 4:How to Get Index of Selected Value in a Datalist
Regexp to Match Every Occurence After N Occurences
Why the Value of Input Elements Are Not Changing
How to Wrap Each Word of an Element in a Span Tag
Get a List of Dates Between Two Dates Using JavaScript
Adding Script Tag to React/Jsx