Reputation: 393
I want to calculate sum of the numbers the user has entered automatically.When the user delete one number the sum should auto calculate.How to calculate sum of array values using jquery.Please help me to solve this problem.
$(document).ready(function(){
$('.form-control').change(function(){
var total = 0;
$('.form-control').each(function(){
if($(this).val() != '')
{
totalvalue += parseInt($(this).val());
}
});
$('#totalvalue').html(totalvalue);
});
})(jQuery);
<h2 style="text-align:center;">INVOICE</h2>
<form id='students' method='post' name='students' action='index.php'>
<div class="table-responsive">
<table class="table table-bordered">
<tr>
<th><input class='check_all' type='checkbox' onclick="select_all()"/></th>
<th>S. No</th>
<th>Job ID</th>
<th>Quantity</th>
<th>Price</th>
<th>Total Price</th>
</tr>
<tr>
<td><input type='checkbox' class='case'/></td>
<td><span id='snum'>1.</span></td>
<td><input class="form-control" type='text' id='txt_jobid' name='txt_jobid[]'/></td>
<td><input class="form-control" type='text' id='txt_quantity' name='txt_quantity[]'/></td>
<td><input class="form-control" type='text' id='txt_price' name='txt_price[]'/></td>
<td><input class="form-control" type='text' id='txt_totalprice' name='txt_totalprice[]'/> </td>
</tr>
</table>
<button type="button" class='btn btn-danger delete'>- Delete</button>
<button type="button" class='btn btn-success addmore'>+ Add More</button>
</div>
</form> Total: <div id="totalvalue">0</div>
SUBMIT FORM
</form>
Upvotes: 0
Views: 7162
Reputation: 12452
Sometime you used total
and sometimes totalValue
. Name the variables the same. And remove the (jQuery)
at the end. It's wrong there.
$(function() {
$('.form-control').change(function() {
var total = 0;
$('.form-control').each(function() {
if( $(this).val() != '' )
total += parseInt($(this).val());
});
$('#totalvalue').html(total);
});
// trigger initial calculation if wanted
.change();
});
Example: https://jsfiddle.net/0zpkow5L/
Initial calculation: https://jsfiddle.net/0zpkow5L/1/
Full working example of your code: https://jsfiddle.net/0zpkow5L/8/
Upvotes: 1