Jquery Table Sum - javascript

I am trying to create rows every time I click the "+" button and sum every column. I can create columns.
But no rows.
This is my code:
$(document).ready(function () {
$("#tabla").click(function () {
$("tr").find("td:last").before('<td><input type="text" value="0"></td>');
$("tr:last").after('<td><input type="text" value="1"></td>');
$("input").each(function () {
$(this).keyup(function () {
newSum.call(this);
});
});
});
});
function newSum() {
var sum = 0;
var thisRow = $(this).closest('tr');
var total = 0;
$(thisRow).find("td:not(.total) input").each(function () {
sum += parseInt(this.value);
});
$(thisRow).find(".total").html(sum);
$('.total').each(function () {
total += parseInt($(this).html());
});
}
http://jsfiddle.net/YQ7LQ/
Thanks in advance.

Added rows and columns sum called on $(document).on('keyup','input',newSum);
Example

I finally resolved the problem.
Here's the code:
//Sum the Rows.
$('#sum_table tr:not(.totalCol) input:text').bind('keyup change', function() {
var $table = $(this).closest('table');
var total = 0;
var thisNumber = $(this).attr('class').match(/(\d+)/)[1];
$table.find('tr:not(.totalCol) .sum'+thisNumber).each(function() {
total += parseInt(this.value);
});
$table.find('.totalCol td:nth-child('+thisNumber+')').html(total);
});
Here is the full code:
DEMO

Related

I want to fixed the decimal places of the textbox value

The function below also calculates the sum on run time. The txtRate is the textbox to be processed for the decimal fix.
$(function() {
$("[id*=txtRate]").val("0");
});
$("body").on("change", "[id*=txtRate]", function() {
var rate = parseFloat($.trim($(this).val()));
if (isNaN(rate)) {
rate = 0;
}
//Update the Rate TextBox.
$(this).val(rate);
//Calculate and update Row Total.
var row = $(this).closest("tr");
$("[id*=lblTotal]", row).html(parseFloat($(".quantity", row).html()) * parseFloat($(this).val()));
//Calculate and update Grand Total.
var grandTotal = 0;
$("[id*=lblTotal]").each(function() {
grandTotal = grandTotal + parseFloat($(this).html());
});
$("[id*=lblGrandTotal]").html(grandTotal.toString());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

Using same JS function for multiple HTML tables?

I have function which adds and delete rows of a table on click of a button i.e add_row. Now i have multiple tables and for which i want to use the same function on the same page.
So below function is for table1, how do i reuse the same function for table2,table3 .. etc? Each table will have its own add_row button i.e, add_row,add_row1, add_row2 etc..
<script type="text/javascript">
$(document).ready(function() {
var rowIdx = 0;
$('#add_row').on('click', function () {
$.each($("#table1 tr"), function() {
if (parseInt($(this).data("id")) > rowIdx) {
rowIdx = parseInt($(this).data("id"));
console.log(rowIdx)
}
});
rowIdx++;
$('#table1').append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id">
<input type="text" name='id${rowIdx}' placeholder='ID' value=""`);
});
$('#table1').on('click', '.remove', function () {
var child = $(this).closest('tr').nextAll();
child.each(function () {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
rowIdx--;
}
);
});
</script>
You mean this?
Don't add and subtract from rowIndex. It is different per table. Use the actual number of rows in the specific table
$(function() {
$('.add_row').on('click', function() {
const $table = $(this).closest("table");
const $rows = $table.find("tr");
let rowIndex = $rows.length;
$table.append(`<tr id="addr${rowIdx}" data-id="${rowIdx}" class="hidden">
<td data-name="id"><input type="text" name='id${rowIdx}' placeholder='ID' value=""</td></tr>`);
});
$(document).on('click', '.remove', function() {
var child = $(this).closest('tr').nextAll();
child.each(function() {
var id = $(this).attr('id');
var idx = $(this).children('.row-index').children('p');
var dig = parseInt(id.substring(4));
idx.html(`Row ${dig - 1}`);
$(this).attr('id', `addr${dig - 1}`);
});
$(this).closest('tr').remove();
});
});

How to change calculation when the row is removed from a table

My problem is the calculations are working fine but when the row is removed the calculations are not updating according to that after creating a new row and after performing calculation only the values are updating..please help me to rectify this problem.
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4)', .
'remove3'
function() {
var total = 0;
var sqty = 0;
var tr = $(this).parent();
var qty = tr.find('td:nth-child(4)').find('input').val();
var rate = tr.find('td:nth-child(5)').find('input').val();
var amount = qty * rate;
tr.find('td:nth-child(6)').find('input').val(amount);
var tbody = tr.parent();
$(tbody).find('tr').each(function() {
total += Number($(this).find('td:nth-child(6)').find('input').val());
sqty += Number($(this).find('td:nth-child(4)').find('input').val());
});
$('#TieTotal').val(total);
$('#SQty').val(sqty);
$('#Grandtot').val(total);
})
Script to create a next row automatically:
$('.tb3').on('keydown', 'input', function(e) {
var keyCode = e.keyCode;
if (keyCode !== 9) return;
var $this = $(this),
$lastTr = $('tr:last', $('.tb3')),
$lastTd = $('td:last', $lastTr);
if (($(e.target).closest('td')).is($lastTd)) {
var cloned = $lastTr.clone();
cloned.find('input').val('');
$lastTr.after(cloned);
}
});
Script to delete row:
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
} else {
alert("Sorry!! Can't remove first row!");
}
});
Let's imagine you have an HTML like (could be a dynamically drawn HTML).
<tr>
<td><input class="Qty" type="text" value="2"/></td>
<td><input class="Rate" type="text" value="200"/></td>
<td><input class="Value" type="text"/></td>
<td><button type="button" class="remove3">X</button></td>
</tr>
Also, let's say you have changed the approach to update the total to be like this, (which is inside document ready). This is a sample code, your actual code may vary. All you need to do is keep the triggering on("keyup change") (or as however you like) inside the document.ready().
$('.Qty').on("keyup change",function(){
var $row = $(this).closest("tr");
var price = 0;
var total = 0;
$('.tb3 tr').each(function() {
var qty = $(this).find('.Qty').val();
var rate = $(this).find('.Rate').val();
var price = qty * rate;
$(this).find('.Value').val(price);
total += parseFloat(price);
});
$('#TieTotal').val(total.toFixed(2));
});
Now, when each time you press the button which has class .remove3 you are correct in terms of removing the row. In the same block you can easilty update the total by triggering the change() event of element which has the class .Qty. (That's how the total is updated in the first place) See below,
$('.remove3').click(function () {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
$('.Qty').trigger('change');
} else {
alert("Sorry!! Can't remove first row!");
}
});
Fiddle,
https://jsfiddle.net/anjanasilva/dykm6wau/
I hope this helps.
Cheers!
Update this line:
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4), .remove3' function(){
i think class '.remove3' not added properly with selectors list.
$(document).on('change', 'tr td:nth-child(6), tr td:nth-child(5), tr td:nth-child(4)', .
'remove3'
function() {
var total = 0;
var sqty = 0;
var tr = $(this).parent();
var qty = tr.find('td:nth-child(4)').find('input').val();
var rate = tr.find('td:nth-child(5)').find('input').val();
var amount = qty * rate;
tr.find('td:nth-child(6)').find('input').val(amount);
var tbody = tr.parent();
$(tbody).find('tr').each(function() {
total += Number($(this).find('td:nth-child(6)').find('input').val());
sqty += Number($(this).find('td:nth-child(4)').find('input').val());
});
$('#TieTotal').val(total);
$('#SQty').val(sqty);
$('#Grandtot').val(total);
})
Script to create a next row automatically:
$('.tb3').on('keydown', 'input', function(e) {
var keyCode = e.keyCode;
if (keyCode !== 9) return;
var $this = $(this),
$lastTr = $('tr:last', $('.tb3')),
$lastTd = $('td:last', $lastTr);
if (($(e.target).closest('td')).is($lastTd)) {
var cloned = $lastTr.clone();
cloned.find('input').val('');
$lastTr.after(cloned);
}
});
Script to delete row:
$(document).on('click', '.remove3', function() {
var trIndex = $(this).closest("tr").index();
if (trIndex > 0) {
$(this).closest("tr").remove();
$('.Qty').trigger('change');
} else {
alert("Sorry!! Can't remove first row!");
}
});

JS function that calculates products qty and options additional taxes

I have this complicated JS function that must calculate the sum of product single price * qty and if there are available options for the product and if the available options have extra tax it has to be added also to the total.
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty option:selected').val();
var selectedoptaddtax = 0.0;
$('.selectedoptionselect option:selected').each(function () {
var selectedoptaddtax = $(this).attr('price');
})
var price = $(this).find('.price').val();
var amount = ((qty * price) + selectedoptaddtax);
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
I have prepared jsfiddle here
In the example I have only 1 product in the basket, but the function must calculate correct if more that 1 product in the basket.
$(document).ready(function () {
update_amounts();
$('.qty').change(function () {
update_amounts();
});
$('.selectedoptionselect').change(function () {
update_amounts();
});
});
You need to add selected option prices.
Code
$(document).ready(function () {
$('.selectedoptionselect, .qty').change(function () {
update_amounts();
}).change();
});
function update_amounts() {
var sum = 0.0;
$('#basketorder > tbody > .product').each(function () {
var qty = $(this).find('.qty').val();
var selectedoptaddtax = 0.0;
//Use find here
$(this).find('.selectedoptionselect option:selected').each(function () {
selectedoptaddtax += +$(this).attr('price'); // You need to add price
})
var price = $(this).find('.price').val();
var amount = (qty * price) + (qty * selectedoptaddtax); //Changes here
sum += amount;
$(this).find('.amount').text('' + amount);
});
$('.total').text(sum);
}
DEMO

Dynamically calculate and display the sum of all tr element

JsFiddle
I am trying to dynamically calculate and display the sum of all tr element whenever a user enters the value of quantity field in my case.
Can someone fix error in my code.
Jquery code:
$("table input").on('change blur input', function() {
var val = this.value;
$(this).closest('tr').find('td:eq(4)').text(function(){
return (+$.trim($(this).siblings(':eq(3)').text()) * +val)
})
$('table tr td:nth-of-type(5)').each(function() {
sum += parseFloat($(this).text().slice(1));
});
$('.sum').text(sum);
});
you need to declare the sum variable
the parseFloat($(this).text().slice(1)) will return NaN when there is not text
why do you use the slice(1) ? you need to parse the whole text.
So
$("table input").on('change blur input', function () {
var val = this.value;
var sum = 0;
$(this).closest('tr').find('td:eq(4)').text(function () {
return (+$.trim($(this).siblings(':eq(3)').text()) * +val)
});
$('table tr td:nth-of-type(5)').each(function () {
sum += parseFloat($(this).text()) || 0;
});
$('.sum').text(sum);
});
Demo at http://jsfiddle.net/KrN7Z/18/
Better Approach
But you should give some classes to some elements in your HTML and it would simplify everything a lot..
<tr>
<td>someno</td>
<td>
<input type="text" placeholder="Some Name" />
</td>
<td>
<input type="text" class="quantity" placeholder="Quantity" />
</td>
<td class="price">50</td>
<td class="total"></td>
<td>something</td>
</tr>
and
$("table input").on('change blur input', function () {
var row = $(this).closest('tr'),
quantity = +row.find('.quantity').val(),
price = parseFloat(row.find('.price').text());
row.find('.total').text(quantity * price);
var sum = 0;
$('.total').each(function () {
sum += parseFloat($(this).text()) || 0;
});
$('.sum').text(sum);
});
Demo at http://jsfiddle.net/KrN7Z/22/
Try this. You need to declare sum, and you need to handle the NaN case.
var sum = 0;
$('table tr td:nth-of-type(5)').each(function() {
var m = parseFloat($(this).text().slice(1));
if (!isNaN(m)) {
sum += m;
}
});
console.log(sum);
As already noted you need to declare sum, handle NaN cases and update the total value on every input. Try this:
$("table input").on('change blur input', function () {
var val = this.value;
var sum = 0;
$(this).closest('tr').find('td:eq(4)').text(function () {
return (+$.trim($(this).siblings(':eq(3)').text()) * +val);
});
$('table tr td:nth-of-type(5)').each(function () {
var k = parseFloat($(this).text());
sum += isNaN(k)?0:k;
$('.sum').text(sum);
});
});

Categories