使用jQuery更改动态创建的输入字段的值

问题描述:

请查看以下jsfiddle;使用jQuery更改动态创建的输入字段的值

https://jsfiddle.net/1kvwxmyb/3/

基本上,代码允许用户“行”添加到发票。当用户选择产品的“增值税税率”时,我需要使用jQuery计算“增值税金额”和“总额”。计算这些数字是基本的数学计算,但目前我甚至无法让jQuery在“增值税金额”和“总额”中设置任何类型的值,而不介意正确的数字!

请帮忙。

jQuery的

// calculate VAT amount and set gross amount 

$(".vat_rate").change(function() { 

    alert("Handler for .change() called."); 

    $(this).nextAll('input').first().val("123"); 

}); 

所以,出发了,有问题的代码更改为以下。

// calculate VAT amount and set gross amount 
$(".nobord").on("change", ".vat_rate", function() { 

    var $row = $(this).closest("tr"); 

    var $qty = $row.find("input[name^='invoice_line_quantity']"); 
    var $amount = $row.find("input[name^='invoice_line_amount']"); 
    //Value of the Qty input 
    console.log($qty.val()); 
    //Value of the Net Amount input 
    console.log($amount.val()); 

    //Now do your math and set the value as below 

    $row.find("input[name^='invoice_line_vat_amount']").val("your_value"); 
    $row.find("input[name^='invoice_line_gross_amount']").val("your_value"); 
}); 

而且由于关闭TD/TR的顺序不对,你的HTML有点搞砸了。看看我所做的更正on this fiddle

希望这是一个良好的开端:)

+0

完美地工作,谢谢! –

我更新了小提琴https://jsfiddle.net/1kvwxmyb/9/

只需添加true参数clone功能,这将导致克隆元素与事件处理程序。

引文从jQuery文档

.clone([withDataAndEvents])

withDataAndEvents(默认值:假)

类型:Boolean

一个布尔指示是否事件处理程序应随着元素一起复制。从jQuery 1.4开始,元素数据也将被复制。

我还在change函数中增加了样本计算。

为了让行,其中的选项改为var $row = $(this).closest("tr");,然后你可以用$row.find("input[name^='invoice_line_vat_amount']")

固定发现输入,现在它的作品为新线https://jsfiddle.net/1kvwxmyb/11/

JS

$(document).on('change', '.vat_rate',function() { 

     var row = $(this).parent().parent().attr("id"); 

     var qty = $("#" + row + " td:nth-child(1) input"); 
     var desc = $("#" + row + " td:nth-child(2) input"); 
     var netam = $("#" + row + " td:nth-child(3) input"); 
     var vatam = $("#" + row + " td:nth-child(5) input"); 
     var grossam = $("#" + row + " td:nth-child(6) input"); 

     vatam.val("123"); 

     //alert("Handler for .change() called."); 

     //$(this).nextAll('input').first().val("123"); 

    }); 
+0

不适用于新元素。 –

+1

更新了我的答案。现在它适用于新元素。 – Boris

一个小变化

// calculate VAT amount and set gross amount 

$(".vat_rate").change(function (event) { 

    $(event.target).parent().parent().find('td:nth-child(3) input').val('0.5'); 

});