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);
});
});
Related
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!");
}
});
I have a form with few fields which does a small calculation. Once all the dropdowns are populated and clicked on Add Button It will display time for specific task. Likewise If you do the calculation couple of times the data will display in the table. and all values in time column will sum add together and display in another row. I have already implemented that. But it keeps adding to the existing value each time.
Refer to the image:
JS Fiddle
$(document).ready(function () {
$('#calculate').click(function () {
let tr = $("<tr/>").appendTo("#data tbody");
$('#calc input, #calc select').each( function (index) {
var input = $(this);
$(tr).append('<td class=row-'+ $(input).attr("id") + '>' + $(input).val() + '</td>');
});
const componentFactor = $(tr).children(".row-component").text();
const units = $(tr).children(".row-units").text();
const total = componentFactor*units;
$(tr).append('<td>' + total + '</td>');
$("#calc")[0].reset();
$("#total").html(sumColumn(5));
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
});
});
The problem is that you are including the total line in your sum function. The .each correctly hits every TD element at the right index, but it is also including the first line.
If you modify your sum function like so, it works.
function sumColumn(index) {
var total = 0;
$("td:nth-child(" + index + ")").each(function() {
if(this.id !== 'total') {
total += parseInt($(this).text(), 10) || 0;
}
});
return total;
}
Same conclusion, you are adding total in your code; you can also use the following option:
function sumColumn(index) {
var total = 0;
$("tr> td:nth-child(" + index + ")").not(':first').each(function(i,item) {
total += parseInt($(this).text(), 10) || 0;
});
return total;
}
You can see it working here: JSFiddle demo
I have an HTML table fetching values dynamically from the database and I have used the sum function to calculate the sum of entire column.
These are my columns where I am fetching the sum total of a column
<td id="totalValue13" style="background-color: darkseagreen;"></td>
<td id="totalValue11" style="background-color: darkseagreen;"></td>
<td id="totalValue12" style="background-color: darkseagreen;"></td>
I want to pass the value of these <td>s into a textbox where I want to calculate these three values. I am using JavaScript to calculate it, given below is a JavaScript code for calculations:
<script type="text/javascript">
function calculate() {
var result = document.getElementById('result');
var el, i = 0, total = 0;
while (el = document.getElementById('v'+(i++))) {
el.value = el.value.replace(/\\D/, "");
total = total + Number(el.value);
}
result.value = total;
if (document.getElementById('v0').value == "" && document.getElementById('v1').value == "" && document.getElementById('v2').value == "") {
result.value = "";
}
}
</script>
I just want to know how to pass the id of an HTML table column here. Thanks.
Use .innerHTML instead of .value since table cells don't have a value. Here is an example on how to calculate the sum of given table cells with each having a separate id.
function calculate()
{
var result = document.getElementById('result');
var v1 = document.getElementById('totalValue11');
var v2 = document.getElementById('totalValue12');
var v3 = document.getElementById('totalValue13');
var el, sum = 0;
var inputList = [v1,v2,v3];
for(var i=0; i<inputList.length; i++)
{
el = inputList[i];
if(el.innerHTML != '' && !isNaN(el.innerHTML))
{
sum += parseFloat(el.innerHTML);
}
}
result.value = sum; // If needed to write to cell use result.innerHTML = sum;
}
// Call it whenever you like
calculate();
td
{
background-color: darkseagreen;
}
<table>
<tr>
<td id="totalValue13">5</td>
<td id="totalValue11">3</td>
<td id="totalValue12">25</td>
</tr>
<tr>
<td colspan="2"><label for="result">Result:</label><input type="text" id="result" value="" readonly="readonly"></td>
</tr>
</table>
Table search functionality for multiple columns using jQuery?
<table>
<tr>
<th><input type="text" id="search" placeholder=" live search"></input></th>
<th><input type="text" id="search" placeholder=" live search"></input></th>
</tr>
<tr><th>Unique ID</th><th>Random ID</th></tr>
<tr><td>214215</td><td>442</td></tr>
<tr><td>1252512</td><td>556</td></tr>
<tr><td>2114</td><td>4666</td></tr>
<tr><td>3245466</td><td>334</td></tr>
<tr><td>24111</td><td>54364</td></tr>
</table>
<br />
<script>
$("#search").on("keyup", function() {
var value = $(this).val();
$("table tr").each(function(index) {
if (index !== 0) {
$row = $(this);
var id = $row.find("td:first").text();
if (id.indexOf(value) !== 0) {
$row.hide();
}
else {
$row.show();
}
}
});
});
</script>
I am trying to implement the search functionality without using jquery plugins..
jsfiddle Link here
http://jsfiddle.net/y9Lxdvps/1/
Use https://api.jquery.com/index/
var inputs = $('table tr:first th input[type=text]');
var trs = $('table tr + tr + tr');
inputs.keyup(function()
{
trs.each(function()
{
var tr = $(this);
var show = inputs.toArray().every(function(input, index)
{
var value = $(input).val();
if (value === '')
{
return true;
}
var number = index + 1;
var td = tr.children('td:nth-child(' + number + ')');
var text = td.text();
return text.indexOf(value) != -1;
});
tr[show ? 'show' : 'hide']();
});
});
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