2013-04-04 85 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