Calculate sum of two dynamically created textboxes using jQuery - javascript

HTML:
<table id="tbl" border="1">
<tr>
<th>Name</th>
<th>Mark1</th>
<th>Mark2</th>
<th>Total</th>
</tr>
<tr>
<td><input type="text"></td>
<td><input type="text" class="cell"></td>
<td><input type="text" class="cell"></td>
<td><b><span id="total_sum_value"></span></b></td>
<td><b><span id="total_sum_value1"></span></b></td>
<th><input class="add-row" data-id="1" type="button" value="+"></th>
</tr>
</table>
JavaScript:
$(document).ready(function(){
var i = $(".add-row").data("id");
$(".add-row").click(function(){
$('#tbl').append('<tr><td><input type="text"></td><td><input type="text"></td><td><input type="text"></td></tr>');
var two = $("input").addClass("cell"+i);
$("#tbl").on('input','.cell'+i,function(){
var sum1 = 0;
$(".cell"+i).each(function() {
var get_val = $(this).val();
sum1 += parseFloat(get_val);
});
$("#total_sum_value1").html(sum1);
});
i++;
});
$("#tbl").on('input','.cell',function(){
var sum = 0;
$('.cell').each(function(){
var get_val = $(this).val();
sum += parseFloat(get_val);
});
$("#total_sum_value").html(sum);
});
});
When you click on the plus sign button, it generates three textboxes. I want to calculate the sum of those textboxes and print it in a span.
Here is a CodePen of my code: https://codepen.io/anon/pen/XBqKVZ?editors=1010

can you try like this:
$('.cell').on('change', function(){
var sum = 0;
var data ={
}
$('.cell').each(function(index, item){
var val = $(item).val();
var get_val = $(this).val();
sum += Number(get_val);
console.log(sum);
});
$("#total_sum_value").html(sum);
});
URL: Jsfiddle

Related

adding up numerical values ​in the table (sum)

I have number inputs
number around 30
I need to sum them all to one field
what I have is below
View:
<table>
<tbody>
<tr>
<td><input class="days_tpu" type="number" id="sth_1"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_2"></td>
</tr>
<tr>
<td><input class="days_tpu" type="number" id="sth_3"></td>
</tr>
</tbody>
// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="time" type="text"></th>
</tfoot>
</table>
I tried:
I try to take all inputs.
and count by length
and sum them
but, it doesn't work
Javascript:
const days_tpu_s = [...document.getElementsByClassName("days_tpu")];
//or
const table = document.querySelector('table');
table.sumInputs = function () {
var inputs = document.getElementsByClassName('days_tpu'),
result = document.getElementById('sum_id_days_tpu'),
sum = 0;
for (var i = 0; i < inputs.length; i++) {
var ip = inputs[i];
if (ip.name && ip.name.indexOf("total") < 0) {
sum += parseInt(ip.value) || 0;
}
}
result.value = sum;
}
sumInputs();
anyone have a good idea?
You can use Array.prototype.map() to get all the input value the use Array.prototype.reduce() to sum them.
Demo:
const days_tpu_s = [...document.getElementsByClassName("days_tpu")];
function sumInputs() {
var sum = days_tpu_s.map(i => Number(i.value)).reduce((a, c) => a + c, 0);
document.getElementById('id_days_tpu').value = sum;
}
days_tpu_s.forEach(function(el){
el.addEventListener('input', sumInputs);
});
<table>
<tbody>
<tr><td><input class="days_tpu" type="number" id="sth_1"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_2"></td></tr>
<tr><td><input class="days_tpu" type="number" id="sth_3"></td></tr>
</tbody>
// field in which it will add up
<tfoot>
<th><input id="id_days_tpu" type="text"></th>
</tfoot>
</table>

Copy and paste from excel spreadsheet into HTML table with cloned rows using Javascript?

I have a table where the user can decide how many rows they wish to add. I've found a script that copy and pastes both columns and rows from excel. It works perfectly from the first 2 existing row's but the function doesn't work properly in any of the cloned rows that get added.
So if you use the function on the first two row's it will split the paste into each row and column (inluding the cloned rows) but if i try paste into a newly added row the function just doesn't work,
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var getTotalRows = $('table > tbody').children().length;
for (var i = -1; i < rowAmmount-1;i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
clone.classList.remove('hidden');
table.appendChild(clone); // add new row to end of table
$('#newRow' + (getTotalRows + i)).children().each(function() {
$(this).children().attr('id', $(this).children().attr('id') + (getTotalRows + i));
});
}}
$('input').on('paste', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="rowAmmount"/>
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Item Name</th>
<th>Long Description></th>
<th>Material</th>
<th>Style</th>
</tr>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="productId"></td>
<td><input id="itemname"></td>
<td><input id="long"></td>
<td><input id="fabric"></td>
<td><input id="style"></td>
</tr>
<tr id= "newRow0">
<td><input id="productId0"></td>
<td><input id="itemname0"></td>
<td><input id="long0"></td>
<td><input id="fabric0"></td>
<td><input id="style0"></td>
</tr>
</tbody>
</table>
You attach the change event handler before you insert the new inputs.
What you need is delegated event handling $('table').on('paste', 'input', function(e){
function cloneRow() {
var rowAmmount = document.getElementById("rowAmmount").value;
var getTotalRows = $('table > tbody').children().length;
for (var i = -1; i < rowAmmount-1;i++) {
var row = document.getElementById("row"); // find row to copy
var table = document.getElementById("table"); // find table to append to
var clone = row.cloneNode(true); // copy children too
clone.id = "newRow" + (getTotalRows + i); // change id or other attributes/contents
clone.classList.remove('hidden');
table.appendChild(clone); // add new row to end of table
$('#newRow' + (getTotalRows + i)).children().each(function() {
$(this).children().attr('id', $(this).children().attr('id') + (getTotalRows + i));
});
}}
$('table').on('paste', 'input', function(e){
var $this = $(this);
$.each(e.originalEvent.clipboardData.items, function(i, v){
if (v.type === 'text/plain'){
v.getAsString(function(text){
var x = $this.closest('td').index(),
y = $this.closest('tr').index()+1,
obj = {};
text = text.trim('\r\n');
$.each(text.split('\r\n'), function(i2, v2){
$.each(v2.split('\t'), function(i3, v3){
var row = y+i2, col = x+i3;
obj['cell-'+row+'-'+col] = v3;
$this.closest('table').find('tr:eq('+row+') td:eq('+col+') input').val(v3);
});
});
});
}
});
return false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="rowAmmount"/>
<button id="add" onclick="cloneRow()">New Row</button>
<button type="button" onclick="submit()">Submit</button>
<table>
<thead>
<tr>
<th>Product Code</th>
<th>Item Name</th>
<th>Long Description></th>
<th>Material</th>
<th>Style</th>
</tr>
</thead>
<tbody id="table">
<tr id="row">
<td><input id="productId"></td>
<td><input id="itemname"></td>
<td><input id="long"></td>
<td><input id="fabric"></td>
<td><input id="style"></td>
</tr>
<tr id= "newRow0">
<td><input id="productId0"></td>
<td><input id="itemname0"></td>
<td><input id="long0"></td>
<td><input id="fabric0"></td>
<td><input id="style0"></td>
</tr>
</tbody>
</table>

jQuery calculate sum text fields if checked

I am trying to calculate the sum of text fields from a row which are checked.
My code works fine, but the problem which I am facing is my only calculate the value of first row only and it to previous result every time instead of adding current text field value.
Here is working fiddle:
https://jsfiddle.net/infohassan/27L6wvgw/
Here is my JS code:
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
$('input[name^="txtChecked"]').each(function() {
var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
calculateTotal();
});
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(){
var val = parseFloat($('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
I cleaned your event handler...
And I made the .each() loop look for the text input which is on the same tr as the checkbox...
UpdatedFiddle
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
//$('input[name^="txtChecked"]').each(function() {
//var countCheckedCheckboxes = $checkboxes.filter(':checked').length;
calculateTotal();
//});
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(){
var val = parseFloat($(this).parents("tr").find('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
$(document).ready(function(){
var $checkboxes = $('input[name^="txtChecked"]');
$checkboxes.change(function() {
// var countCheckedCheckboxes = $checkboxes.find(':checked').length;
calculateTotal();
});
});
function calculateTotal() {
var total = 0;
$('input[name^="txtChecked"]:checked').each(function(index, item){
var parent = $(item).closest('tr');
var val = parseFloat(parent.find('input[name^="txtCostAmount"]').val());
total += val;
});
$('input[name="txtNetAmount"]').val(total);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<thead>
<tr>
<th></th>
<th>Items</th>
<th>Cost</th>
</thead>
<tbody>
</tbody>
<tr>
<td><input name="txtChecked0" type="checkbox"></td>
<td>Item Name 1</td>
<td><input class="form-control input-sm" name="txtCostAmount0" value="3500" type="text"></td>
</tr>
<tr>
<td><input name="txtChecked1" type="checkbox"></td>
<td>Item Name 2</td>
<td><input class="form-control input-sm" name="txtCostAmount1" value="4500" type="text"></td>
</tr>
<tr>
<td><input name="txtChecked2" type="checkbox"></td>
<td>Item Name 3</td>
<td><input class="form-control input-sm" name="txtCostAmount2" value="4500" type="text"></td>
</tr>
</table>
<p>NetAmount <input class="form-control" name="txtNetAmount" value="0.00" readonly="" type="text"></p>

How do I select two separate inputs in each tr using jQuery?

I have this html table:
<table id='table1'>
<tr>
<td>String</td>
<td><input type='text' id='first-input-01'></input></td>
<td><input type='text' id='second-input-01'></input></td>
</tr>
<tr>
<td>String</td>
<td><input type='text' id='first-input-02'></input></td>
<td><input type='text' id='second-input-02'></input></td>
</tr>
<tr>
<td>Total:</td>
<td> </td>
<td>(total goes here)</td>
</tr>
</table>
and using jQuery, I want to find the value of #first-input-xx and multiply it by #second-input-xx for each table row, adding up each row to an overall total. However, I'm finding it difficult to select each input for each table row. I'm trying:
var total = 0;
$("#table1 tr").each(function() {
var amount1 = $(this).children("td:nth-last-child(2) input").val();
var amount2 = $(this).children("td:last input").val();
total = total + (parseFloat(amount1) * parseFloat(amount2));
});
Appreciative of any help.
You cannot use .children() as you are trying to find the input element, instead use .find()
var total = 0;
$("#table1 tr").each(function () {
var amount1 = $(this).find("td:eq(-2) input").val();
var amount2 = $(this).find("td:last input").val();
total += (parseFloat(amount1) * parseFloat(amount2)) || 0;
});
alert(total)
$('button').click(function() {
var total = 0;
$("#table1 tr").each(function() {
var amount1 = $(this).find("td:eq(-2) input").val();
var amount2 = $(this).find("td:last input").val();
total += (parseFloat(amount1) * parseFloat(amount2)) || 0;
});
alert(total)
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table id='table1'>
<tr>
<td>String</td>
<td>
<input type='text' id='first-input-01'></input>
</td>
<td>
<input type='text' id='second-input-01'></input>
</td>
</tr>
<tr>
<td>String</td>
<td>
<input type='text' id='first-input-02'></input>
</td>
<td>
<input type='text' id='second-input-02'></input>
</td>
</tr>
</table>
<button>Test</button>
Try this: use eq()
var total = 0;
$("#table1 tr").each(function () {
var input = $(this).find('input');
if (input.length == 2) {
total += input.eq(0).val() * input.eq(1).val();
}
console.log(total)
});
DEMO
$("#table1 tr").each(function() {
var amount1 = $(this).find("td:nth-child(2)").val();
var amount2 = $(this).find("td:nth-child(3)").val();
total = total + (parseFloat(amount1) * parseFloat(amount2));
});
Here i have added few codes. please check it out.
$("#calculate_btn").click(function(){
var total=0;
var row_mux=1;
$("#table1 tr").each(function(key,val){
$(val).find("input").each(function(k,v){
row_mux*=parseFloat($(v).val());
});
total=row_mux++;
});
alert(total);
$("#table1 tr:last").find("td:last").html(total);
});
demo

Sum of all values in a class tag

I want the Grand Total calculation now.. I want the sum of all the values in the Amount field... I tried tis code but its not working...
$(".amt").each(function(){
total=total+(parseInt($(this).val()))
});
According to the following HTML:
<table>
<tr>
<td><input class="amt" /></td>
</tr>
<tr>
<td><input class="amt" /></td>
</tr>
</table>
<div id="total"></div>
The JS would be:
$('table').focusout(function() {
var sum = 0;
$('.amt').each(function(){
if (this.value != "") {
sum += parseFloat(this.value);
}
});
$('#total').html("Grand total: " + sum);
});
JsFiddle
If you are adding these dynamically, you will need to have something like this:
$(document).on('click', '.count', function()
{
var total = 0;
$(".amt").each(function()
{
total=total+(parseInt($(this).val()))
});
alert(total);
});

Categories

Resources