0
我正在用jQuery構建發票應用程序。應用程序可以自動計算價格,並在按下「ADD LINE」按鈕時生成新的輸入字段。我遇到的問題是輸入字段的第一行始終有效,但只要您開始添加新字段,價格和數量數字就不會被應用程序計算。最糟糕的是,控制檯沒有提及我的腳本中的任何錯誤,所以我真的不知道發生了什麼。爲什麼動態添加新字段後,輸入字段上的價格無法運行?
感謝,
這裏是我的代碼:
// Core functions for calculations
$('input[name=r],input[name=p]').change(function(e) {
var total = 0;
var $row = $(this).parent();
var rate = $row.find('input[name=r]').val();
var pack = $row.find('input[name=p]').val();
total = parseFloat(rate * pack)*1;
//update the row total
$row.find('.amount').html((total).toFixed(2));
var total_amount = 0;
var tax = 1.06;
$('.amount').each(function() {
//Get the value
var am= $(this).text();
console.log(am);
//if it's a number add it to the total
if (IsNumeric(am)) {
total_amount += parseFloat(am, 10);
}
// Get total with tax
taxTotal = (tax * total_amount);
});
// Total with out tax
$('.total_amount').html('<p> $ '+(total_amount).toFixed(2)+'</p>');
// Total with tax
$('.after_tax').html('<p> $ '+(taxTotal).toFixed(2)+'</p>');
});
//if it's a number add it to the total
function IsNumeric(input) {
return (input - 0) == input && input.length > 0;
}
// generate a new row
function AddRow(){
var wrapper = $('.input_fields_wrap');
var addButton = $('#add_row');
var x = 1;
$(addButton).click(function(){
x++;
$(wrapper).append('<div><input class="description" type="text" maxlength="255" placeholder="Enter Description" value=""/><input name="r" class="rate qty" type="text" maxlength="255" placeholder="0" size="5" value=""/><input name="p" class="pack price" type="text" maxlength="255" placeholder="$ 0.00" size="5" value=""/><span id="amount" class="amount">0.00</span><a class="btn btn-danger removeRow">X</a></div>');
});
// Remove row
$(wrapper).on('click', '.removeRow', function(){
$(this).parent('div').remove();
x--;
});
}
AddRow();
a [mcve]會很棒 –
這是因爲您需要再次添加新元素才能從DOM中獲取它們。 OR或or or正確使用帶事件委派的'.on()'方法。 –
我剛剛發佈我的代碼:-) – Shark