2015-06-20 132 views
1

請查看以下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"); 

}); 

回答

1

所以,出發了,有問題的代碼更改爲以下。

// 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

完美地工作,謝謝! –

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']")

0

固定發現輸入,現在它的作品爲新線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

0

一個小變化

// 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'); 

}); 
相關問題