Javascript:合并具有ruby代码的公用表行?

时间:2018-03-20 00:37:07

标签: javascript jquery html ruby-on-rails ruby

Javascript的新手,我试图创建一个函数,当它们具有相同的值(在这种情况下,年份(#pin))时合并行并添加它们的数字(#price)。我的代码不起作用,但它似乎不会导致我的网页出现任何错误。

表格行html.erb:

<tr class="<%= payment_paid(f.paid)%>" id="paidrow">
     <td>
       <% if !f.paid %>
       <%= check_box_tag "pin_number[]", f.id, checked= !f.paid? %>
       <%end%>
     </td>

     <td id="pin"><%= f.year %></td>
     <td><%= f.quarter %></td>
     <td align="right" id="price"><%= number_to_currency(f.amount, unit: "", 
     precision: 2)%></td>
  </tr>

使用Javascript:

$("#paidrow").each(function() {
      var thisId = $(this).find('#pin').text();
      var sumVal = parseFloat($(this).find('#price').text());

      var $rowsToGroup = $(this).nextAll('tr').filter(function() {
        return $(this).find('#pin').text() === thisId;
      });

      $rowsToGroup.each(function() {
        sumVal += parseFloat($(this).find('#price').text());
        $(this).remove();
      });

      $(this).find('#price').text(sumVal);
    });

以上代码取自此处发布的答案:

how to combine morethan 2 duplicate rows and sum the value in html table using jquery

1 个答案:

答案 0 :(得分:0)

checked= !f.paid?这不对......应该是checked: !f.paid?

同样:id="paidrow"id="price"

在html中,ID必须是唯一的。如果你在多行中有相同的东西,那将破坏html标准。

尝试使用class代替id来匹配多个类似的内容,并使用某些内容来统一ID,例如:

class="paidrow" id="paid_row_<%= f.id %>"