2013-05-01 149 views
1

的多个部分和字段这是我正在做的。我有一组div。每套div都可以包含一个节标题和一个项目列表。每件商品都有与之相关的价格。因此,拆除部分下的第1项价格为150.00。 “拆除”一节中的第2项价格为200.00。每个项目旁边都有一个用户可以输入数字值的输入字段。该值然后乘以项目价格。因此,在项目1(150.00)旁边是我输入2的字段。在下一个div中,我显示总数。所以150.00 x 2 = 300.00。Jquery遍历表

我可以为该部分下的每个项目执行此操作。然后,我将所有项目汇总到各部分旁边的全球价格中。

下面是我在做什么的样本:

$(document).ready(function() { 
    $(".demolition_num").each(function() { 
    $(this).keyup(function(){ 
     calculateDemSum(); 
    }); 
    }); 
}); 


function calculateDemSum() { 
    var sum = 0; 
    $(".demolition_num").each(function(){ 
    if(!isNaN(this.value) && this.value.lenth != 0){ 
     var unitCost = $(".unit_cost1").text(); 
     var _parent = $(this).parent(); 
     var total = _parent.prev().html(); 
     sum += parseFloat(this.value * total); 
     var subtotal = this.value * total; 
     $(_parent).next().html(this.value * total); 
    } 
    else if (this.value.length !=0){ 
    } 
    }); 

    $(".cost1").text(sum.toFixed(2)); 
    $("#cost1").val(sum.toFixed(2)); 
} 

您可以查看这里的所有代码:http://jsfiddle.net/pmetzger/Xeu2T/3/

正如你可以在现在我有打电话给每一个看到的jQuery部分独立 其他人,因为我不想计算所有的领域,只是我正在修改的领域。

所以问题是,我可以避免必须添加每个部分输入类型ID作为触发计算的关键,并确保总数得到正确放置?

注意:此代码可能会被复制,但相关的数据会有所不同。所以在下一个客户名单上,它可能不是拆迁,而是Demo等等。

任何帮助将不胜感激。

回答

0

首先几个指针:

  1. 你并不需要一个each()循环中绑定的事件,只是 绑定到一个标准的选择会结合适合 该选择的所有元素。
  2. 您也有多个具有相同ID的<tr>元素。
  3. 你不需要对隐藏标签

新的工作fiddle here和代码size属性:

$(document).ready(function() 
{ 
    // Bind the event 
    $("#calc").on("keyup", "input[type='text']", function() 
    { 
     calculateSum(this); 
    }); 
}); 

function calculateSum(element) 
{ 
    var sum = 0; 
    var $this = $(element); 
    var targetClass = $this.attr("class"); 

    // Process each element with the same class 
    $("." + targetClass).each(function() 
    { 
     var thisVal = $(this).val(); 

     // Count invalid entries as 0 
     if(isNaN(thisVal) || thisVal.length === 0) 
     { 
      thisVal = 0; 
     } 
     else 
     { 
      thisVal = parseFloat(thisVal); 
     } 

     // Get the unit cost and calculate sub-total 
     var unitCost = parseFloat($(this).parent().prev("td.unit_cost").text()); 
    var subTotal = thisVal * unitCost; 
    sum += subTotal; 
     $(this).parent().next("td").text(subTotal); 
    }); 

    var $item = $this.closest("tr").prevAll(".item").first(); 
    $item.find("input.section_cost").val(sum.toFixed(2)); 
    $item.find("td.section_cost").text(sum.toFixed(2)); 
} 

注意,我稍微修改你的HTML - 我改变了多个<tr id="item">使用类,我移动这些行以更好地定位您的小节总计,我添加了小节总计(隐藏输入和显示值),我添加了一个类到您的单位值字段,我添加了一个id到表。

+0

多数民众赞成在奇妙....感谢很多让这回这么快。 – pjmetzger 2013-05-02 01:52:47