我使用nested_form创建包含多个invoice_line_items的发票表单。然后我在用户输入信息时使用javascript计算总数。除了fieldRemoved侦听器事件未触发重新计算之外,一切正常。这是我的js:
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"
为什么这不起作用?谢谢!
答案 0 :(得分:1)
原因是当您删除带有nested_form
gem的字段时,字段本身不会被删除,只会被隐藏。具体来说,它会将style="display: none;"
添加到.fields
元素,因此您需要在循环计算小计时排除这些元素。更改multInputs()
中的循环以排除隐藏的元素应解决问题,例如使用:
$("tr.txtMult:visible").each(function () { ... })
// or
$("tr.txtMult").not("[style]").each(function () { ... })