2013-04-04 86 views
0

我正在使用nested_form来创建具有多个invoice_line_items的发票表单。然后,我使用JavaScript来计算总数,而用户输入他们的信息。除了fieldRemoved监听器事件没有触发重新计算之外,一切正常。这是我的js:nested_form fieldRemoved事件没有触发正确的重新计算

function calculate_invoice() { 
    $(".txtMult input").keyup(multInputs); 

    function multInputs() { 
    var mult = 0; 
    // for each row: 
    $("tr.txtMult").each(function() { 
     // get the values from this row: 
     var $quantity = $('.quantity', this).val(); 
     var $rate = $('.rate', this).val(); 
     var $total = ($quantity * 1) * ($rate * 1); 
     // set total for the row 
     $('.multTotal', this).text($total); 
     mult += $total; 
     }); 
    $("#grandTotal").text(mult); 
    } 
} 

$(document).ready(function() { 
    calculate_invoice(); 
}); 

$(document).on('nested:fieldAdded', function(event){ 
    calculate_invoice(); 
}); 

// not working 
$(document).on('nested:fieldRemoved', function(event){ 
    calculate_invoice(); 
}); 

我放置了一个控制台输出,以确保js函数正确触发,它是。但是,页面不会重新计算。这是我的页面视图:

%table.table#line_items_table 
     %thead 
      %td   
      %td Description 
      %td Quantity 
      %td Rate 
      %td Total 
     %tbody#line-items 
      = f.fields_for :invoice_line_items, :wrapper => false do |line_item| 
      %tr.txtMult.fields 
       %td= line_item.link_to_remove "X" 
       %td= line_item.text_field :description, :label => false 
       %td= line_item.text_field :quantity, :class => "input-mini quantity", :label => false, :id => "quantity" 
       %td= line_item.text_field :rate, :class => "input-mini rate", :label => false, :id => "rate" 
       %td.multTotal 0 
     %p#grandTotal.pull-right 0 
     %p= f.link_to_add "Add", :invoice_line_items, :data => { :target => "#line-items" }, :id => "hello" 
     .form-actions 
     = f.submit "Preview Invoice", :class => "btn btn-primary pull-right" 

为什么不能正常工作?谢谢!

回答

1

原因是当您使用nested_form宝石删除字段时,字段本身不会被删除,只能隐藏。具体而言,它会将style="display: none;"添加到.fields元素,因此您需要在循环计算小计时排除这些元素。改变你的multInputs()循环排除隐藏要素应该用解决问题,例如:

$("tr.txtMult:visible").each(function() { ... }) 
// or 
$("tr.txtMult").not("[style]").each(function() { ... }) 
+0

我该怎么传递到[风格]格式是什么? – 2013-04-04 02:18:27

+0

不需要替换任何东西,只需按照上面所述完成即可。 '[style]'是一个css选择器,它将匹配具有'style'属性集的任何元素,它将匹配'nested_form'隐藏的元素。 – 2013-04-04 02:28:46

+0

$(“tr.txtMult:visible”)。each(function(){working too ...使用的任何缺点:visible? – 2013-04-04 02:29:31