为什么输入字段的价格在动态添加新字段后无效?

时间:2016-04-29 01:23:06

标签: jquery

我正在使用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();  

1 个答案:

答案 0 :(得分:0)

更改事件未绑定到任何动态添加的输入元素。在祖先选择器上使用jQuery的.on()方法:

$('body').on('change', 'input[name=r],input[name=p]', (function(e) {
    // ...

理想情况下,您应该在呈现页面时选择与DOM中存在的输入最接近的祖先。

相关问题