I am making an entry list that will automatically add up the amount and show the total amount at the bottom. I am trying to implement onchange into the function but unsure how to do it. My current code only get to sum up the amount if the value is fixed and need to refresh page.
Thanks in advance.
var rows = $("#data tr:gt(0)");
var tamount;
rows.children("td:nth-child(3)").each(function() {
tamount = parseInt($(this).html());
});
$("#total_amount").html(tamount);
| No | Description | Amount |
| -- | ----------- | ------ |
| 1 | abc | 2.50 |
| 2 | efg | 1.90 |
| 3 | tyu | 5.00 |
| 4 | mno | 7.90 |
--------------------
Total Amount : 17.30
--------------------
<table id="data">
<tr>
<th>No</th>
<th>Description</th>
<th>Amount</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
</table>
<div>
<h5>Total Amount :<input type="number" name="total_amount" readonly></h5>
</div>
CodePudding user response:
Try this code in your javascript:
$(document).ready(function () {
$('input[name="total_amount"]').val(calcSum());
$('input[name="amount"]').change(function () {
$('input[name="total_amount"]').val(calcSum());
});
});
function calcSum() {
var tamount = 0;
$('input[name="amount"]').each(function() {
tamount = parseInt(($(this).val() ? $(this).val() : 0));
});
return tamount;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="data">
<tr>
<th>No</th>
<th>Description</th>
<th>Amount</th>
</tr>
<tr>
<td>1</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>2</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
<tr>
<td>3</td>
<td><input type="text" name="descrpt"></td>
<td><input type="number" name="amount"></td>
</tr>
</table>
<div>
<h5>Total Amount :<input type="number" name="total_amount" readonly></h5>
</div>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
Explanation:
- Instead of getting the child elements, you can directly use
$('input[name="amount"]')
to refer to each input element $('input[name="amount"]').each()
will iterate over each number field- I created a new function
calcSum()
to do the calculation part. - You should use
.val()
for input elements instead of.html()
- Note,
change()
will require you to lose focus from the field, alternately, you can usekeyup()
No change in html required.