Calculate sum of html element’s values with specific class names using Jquery.
This code is useful in get sum of the elements values of specific class ,id.
Something like the following should work for you:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('.ttl_amt').on('change', function () {
var ttl_amt=0;
$(".ttl_amt").each(function() {
var amt=parseInt($(this).val());
if(amt>0)
{
ttl_amt=ttl_amt + parseInt($(this).val());
}
});
$("#total_amount").val(ttl_amt);
});
});
</script>
</head>
<body>
<p>How to get sum of html element's values with specific class names.</p>
<table>
<tr>
<td>Amount 1</td>
<td><input type="text" name="amount_1" id="amount_1" class="ttl_amt"></td>
</tr>
<tr>
<td>Amount 1</td>
<td><input type="text" name="amount_1" id="amount_1" class="ttl_amt"></td>
</tr>
<tr>
<td>Amount 2</td>
<td><input type="text" name="amount_2" id="amount_2" class="ttl_amt"></td>
</tr>
<tr>
<td>Amount 3</td>
<td><input type="text" name="amount_3" id="amount_3" class="ttl_amt"></td>
</tr>
<tr>
<td>Amount 4</td>
<td><input type="text" name="amount_4" id="amount_4" class="ttl_amt"></td>
</tr>
<tr>
<td>Total Amount</td>
<td><input type="text" name="total_amount" id="total_amount" ></td>
</tr>
</table>
</body>
</html>
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 |
<!DOCTYPE html> <html> <head> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script> <script> $(document).ready(function(){ $('.ttl_amt').on('change', function () { var ttl_amt=0; $(".ttl_amt").each(function() { var amt=parseInt($(this).val()); if(amt>0) { ttl_amt=ttl_amt + parseInt($(this).val()); } }); $("#total_amount").val(ttl_amt); }); }); </script> </head> <body> <p>How to get sum of html element's values with specific class names.</p> <table> <tr> <td>Amount 1</td> <td><input type="text" name="amount_1" id="amount_1" class="ttl_amt"></td> </tr> <tr> <td>Amount 1</td> <td><input type="text" name="amount_1" id="amount_1" class="ttl_amt"></td> </tr> <tr> <td>Amount 2</td> <td><input type="text" name="amount_2" id="amount_2" class="ttl_amt"></td> </tr> <tr> <td>Amount 3</td> <td><input type="text" name="amount_3" id="amount_3" class="ttl_amt"></td> </tr> <tr> <td>Amount 4</td> <td><input type="text" name="amount_4" id="amount_4" class="ttl_amt"></td> </tr> <tr> <td>Total Amount</td> <td><input type="text" name="total_amount" id="total_amount" ></td> </tr> </table> </body> </html> |