'jquery calculate value in input function
I need to jQuery to sum up at #totalpprice append from jQuery. It doesnt seem to work once append/added to oi id="addhereform"
<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>');
});
live demo here --> http://jsfiddle.net/koto/cTWCq/
Solution 1:[1]
Because you're adding elements dynamically, you need to use .on() instead of .change() to bind your event handler. You also need to change your logic so that you're locating the sibling cells to perform your calculation...
$(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/
You are also adding duplicate ID's to the page. Consider using unique IDs and use classes in your selectors.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Anthony Chu |
