Reputation: 4570
I have some table & i need to calculate Column values.In my scenario i need to calculate Total Item Price 99 + 55 = 154 to Sub Total Row.In here my SubTotal Calculation not working.
My Code(part of my Table Creation)
$option.each(function () {
if ($(this).prop('selected')) {
var txtId = 'txtQty' + i;
var lblId = 'lblQty' + i;
var row = $('<tr><td>' + $(this).text() + '</td><td>' + $(this).attr('RetailPrice') + '</td><td>' + $(this).attr('WholesalePrice') + '</td><td>' + '<input type="text" id="' + txtId + '">' + '</td><td> <button type="button" class="btn btn-warning btn-xs btncalc">Calculate</button></td><td class="tot"><label for="tempprice" id="' + lblId + '"></label></td><td><img id="imgdel" src="../../Images/delete.png" alt="" onclick="deleteclick(this)" title="Delete" /></td></tr>');
table.append(row);
i++;
}
});
var row2 = $('<tr><td>' + "SubTotal" + '</td><td></td><td></td><td></td><td></td></tr>');
table.append(row2);
$('#product-load-tbl').append(table);
});
Calculation Part
$('.btncalc').live('click', function () {
debugger;
var row = $(this).parents("tr:first");
var rowval = $(row).find("td:eq(1)").html();
var inpval = $(row).find("td:eq(3) input").val();
if (inpval != null || inpval != 0) {
var result = (rowval * inpval);
}
else {
var result = 0;
}
$(row).find("td:eq(5)").html(result);
var lstrow = $(this).parents("tr:last"); // this sub total calculation not working
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
})
Upvotes: 0
Views: 1456
Reputation: 74738
You can change this:
$.each($('.tot'), function (element) {
$(lastrow).find("td:eq(5)").html(element);
});
to this:
var total = 0; // intialise a var with value 0
$('.tot').each(function (i, element) { // loop the selected item in each row
total += +$(this).text(); // cast the string to integer and add it to total
});
$(lastrow).find("td:eq(5)").text(total); // then at last place the total
And for a short note:
.live()
is now removed from the latest jQuery versions, so if you are using version 1.7+
then you can move your code to .on()
method to delegate the event. Syntax is something like this for event delegation:
$(static_parent).on(event, selector, callback);
$(static_parent)
is the element which was available when the relative dom is ready and it was available at that time before appending any dynamic dom element in the page.
so in your case:
$('table_ID/Class').on('click', '.btncalc', function(){
//...all the stuff with .live goes here
});
Upvotes: 1