Reputation: 673
I created a table, sum columns and rows. The problem I have is:
When I click the "+" button, I can sum the rows but I have a Problem with the columns. I think it's a problem with KeyUp, but I don't know.
This is the code that sum Columns:
$('#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);
});
Code that increment rows and columns:
$("#tabla").click(function () {
$("tr").find("td:last").before('<td><input type="text" value="0"></td>');
var linea = $('tr:first').html();
$('tr:last').before('<tr>'+linea+'</tr>');
$('tr').last().find("td").last.html('<td>hola</td>');
});
Upvotes: 0
Views: 2188
Reputation: 25537
I've changed the +
button click in your fiddle
$("#tabla").click(function () {
$("#sum_table tr:last-child").before('<tr><td><input type="text" value="0"></td><td><input type="text" value="0"></td><td><input type="text" value="0"></td><td class="total"> 0 </td></tr >');
});
Edit
You need to use on
delegate for newly created textbox keyup event,
$(document).on('keyup change', '#sum_table tr:not(.totalCol) input:text', 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);
});
Edit
$("#tabla").click(function () {
$("#sum_table tr:last-child").before("<tr>" + $("#sum_table tr:eq(0)").html() + "</tr>");
$("tr:not(:last-child)").each(function () {
var classname = $(this).find("td:last-child").index() + 1;
$(this).find("td:last-child").before('<td><input class="sum' + classname + '" type="text" value="0"></td>');
});
$("#sum_table tr:last-child").append("<td>0</td>");
});
Upvotes: 1