rafitio rafitio - 8 months ago 45
jQuery Question

how to calculate the sum of dynamically column with jquery

I've been create a table row with jquery, the column id is the id of data that have been selected. How can i calculate the sum of 'total_price' column which the id is dynamically (based on data id) ?

enter image description here

here my jquery script

function getCorporateService(id){
//get data and parsing to coloumn
$.get("{{ url('salesorder/service')}}/"+id, function(data){
$.each(data, function (index, element){

$br = "<tr id='item'>";
$br += "<td> <input class='input-small' type='text' id='order_identifier' name='order_identifier' readonly></td>";
$br += "<td><input class='input-small' type='text' id='service["+id+"]' name='service["+id+"]' value='"+element.service_name+"' readonly></td>";
$br += "<td><select id='order_type["+id+"]' name='order_type["+id+"]'> <option> - </option> <option value='add'>Add</option> <option value='change'>Change</option> <option value='cancel'>Cancel</option> </select></td>";
$br += "<td><input class='input-small' type='text' id='select_plan["+id+"]' name='select_plan["+id+"]'></td>";
$br += "<td><input class='input-mini' type='text' id='qty["+id+"]' name='qty["+id+"]' value='1' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><input class='input-small' type='text' id='unit_price["+id+"]' name='unit_price["+id+"]' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><input class='input-small' type='text' id='total_price["+id+"]' name='total_price["+id+"]' onChange='getTotalPrice("+id+")'></td>";
$br += "<td><textarea class='input-small' id='notes["+id+"]' name='notes["+id+"]'></textarea></td>";
$br += "</tr>";


Answer Source

Use the starts with selector inside the getTotalPrice

function getTotalPrice() {
  var total = 0; 
  $("[id^='total_price']").each(function() { 
    var val = $(this).val();
    total += isNaN(val) || $.trim(val)=="" ? 0 : parseFloat(val); // or parseInt(val,10);
  $("#total").text(total.toFixed(2)); // or (total) if an int

You should give each of the changeable inputs a classname and assign a handler - onkeyup for example and use delegation:

$(function() {
  $(".corporatesvc").on("keyup",".changeable",function() {
    if (this.id.indexOf("qty")==0 ) {
      // here you can update siblings