2014-02-23 177 views
0

我需要jQuery總結從#totalpprice追加jQuery。它似乎沒有工作,一旦追加/加OI ID =「addhereform」jquery計算輸入函數中的值

<form method="get" action="here" onsubmit=""> 
     <input type="text" id="pname" name="pname" value="Product Name"/> 
     <input type="number" id="pqty" name="pqty" value="3"/> 
     <input type="text" id="pprice" name="pprice" value="2.80"/> 
     <input type="text" id="totalpprice" name="totalpprice" value="" readonly/> 
     <input type="button" id="padd" name="padd" value="add"/> 
    </form> 

<ol id="addhereform"> 
<li></li> 
</ol> 

var sumpprice = $('#pprice').val(); 
$('#pqty').change(function(){ 
    var sumpqty = $(this).val(); 
    var sumtotal = (sumpprice * sumpqty).toFixed(2); 
    $('#totalpprice').val(sumtotal); 
}) 
.change(); 

$('#padd').click(function(){ 
    var pname = $('#pname').val(); 
    var pqty = $('#pqty').val(); 
    var pprice = $('#pprice').val(); 
    var totalpprice = (pqty * pprice).toFixed(2); 
    $('#addhereform li:last').append('<input type="text" id="pname" name="pname" value="' + pname + '"/><input type="number" id="pqty" name="pqty" value="' + pqty + '"/><input type="text" id="pprice" name="pprice" value="' + pprice + '"/><input type="text" id="totalpprice" name="totalpprice" value="' + totalpprice + '"/></li><li>'); 
}); 

現場演示在這裏 - >http://jsfiddle.net/koto/cTWCq/

回答

0

因爲你動態地添加元素,你需要使用.on()代替.change()綁定你的事件處理程序。你還需要改變你的邏輯,這樣你定位同級小區來執行你的計算...

$(document).on('change', '#pqty', function(){ 
    var $this = $(this); 
    var sumpprice = $this.siblings('#pprice').val(); 
    var sumpqty = $this.val(); 
    var sumtotal = (sumpprice * sumpqty).toFixed(2); 
    $this.siblings('#totalpprice').val(sumtotal); 
}); 

的jsfiddle:http://jsfiddle.net/cTWCq/2/

您還添加重複ID的頁面。考慮使用唯一的ID並在選擇器中使用類。

+0

很酷的thx。我正在考慮增加數字。 兄弟姐妹是否也是做這項工作的人? – user3322550

+0

'兄弟姐妹()'在父母的直接孩子中尋找匹配。在你的情況下,它會匹配相同的形式或相同的元素。 –

+0

偉大thx!我學到了新的東西 – user3322550