2016-04-29 5 views
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(); 
+1

[mcve]は大変です –

+0

これはDOMから取得するために必要な新しい要素を追加した後に発生します。 OR or or orイベント・デリゲーションとともに '.on()'メソッドを正しく使用してください。 –

+0

私はコードを投稿しました:-) – Shark

答えて

0

変更イベントは、任意の動的に追加された入力要素にバインドされていません。祖先セレクタでjQueryの.on()メソッドを使用します。

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

は、理想的には、ページがレンダリングされるときにDOMに存在する入力に最も近い祖先を選択する必要があります。

+0

はい、感謝しました:-) – Shark

関連する問題