I am quite new with jQuery, the following code is a collage of 2 different codes I found to achieve my objective
I have a table with a an image that when clicked it removes a table row, that is the first part of the below code.
The second part of the script finds the sum of all the table rows
I am trying to make it so that when you remove a row the sum also changes accordingly. So when you remove a table row the amount in that table row will be subtracted from the total. I need the sum to change according to the row you delete
jQuery part that removes the table row
$(document).ready(function(){
$('table#FeatureMatrix td a.delete').click(function()
{
{
var id = $(this).parent().parent().attr('id');
var data = 'id=' + id ;
var parent = $(this).parent().parent();
parent.fadeOut('slow', function()
{$(this).remove();});
return false;
}
});
Part of jQuery that calculates the sum of all table rows
$(document).ready(function() {
//this calculates values automatically
calculateSum();
$(".txt").live("keydown keyup", function() {
calculateSum();
});
});
function calculateSum() {
var sum = 0;
//iterate through each textboxes and add the values
$(".txt").each(function() {
//add only if the value is number
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
else if (this.value.length != 0){
}
});
$("#sum").html(sum.toFixed(2));
}
If somebody wants to see the example page on the web this is the link http://webiceberg.net/Prices.php, you can also view the source of the page if you need more detail on the code.
You simply need to call calculateSum() when you delete the row (tidied the code up a bit as well!):
Note that it has to be done after the $(this).remove() inside the callback otherwise you will call calculate before actually removing the row.
If you are concerned about it calling
calculateSumdirectly then fire a custom event and listen for that and then recalculate:Then listen for this event: