How to calculate total price using keyup function in jquery or javascript
The keyup() method triggers the keyup event, or attaches a function to run when a keyup event occurs.
You can use parseFloat and parseInt to get the values from the other inputs, toFixed to ensure the final value looks like currency (remove that if it’s not needed), and provide a fallback of 0 in case something can’t be parsed.
HTML code
<div class="col-md-12" style="padding-bottom: 10px;">
<div class="col-md-2">
<b>Amount:</b>
</div>
<div class="col-md-2">
<input type="text" value="0" class="form-control ChangeAmount">
</div>
</div>
<div class="col-md-12" style="padding-bottom: 10px;">
<div class="col-md-2">
<b>Total Amount:</b>
</div>
<div class="col-md-2">
<input type="text" readonly="" id="totalamount1" value="20" class="form-control" />
</div>
</div>
<div class="col-md-12" style="padding-bottom: 10px;">
<div class="col-md-2">
<b>Total Paid:</b>
</div>
<div class="col-md-2">
<input type="text" value="0" readonly="" class="form-control tpaid" />
</div>
</div>
<div class="col-md-12" style="padding-bottom: 10px;">
<div class="col-md-2">
<b>Balance:</b>
</div>
<div class="col-md-2">
<input type="text" readonly="" value="20" class="form-control BalanceAmount" />
<input type="hidden" id="returned_change" name="returned_change" value="0" />
</div>
</div>
Jquery and JavaScript Code
<script>
$('document').ready(function(){
$('.ChangeAmount').keyup(function(){
var total_paid = $(this).val();
if (total_paid == 0 || total_paid == '' ) {
total_paid = 0;
}
$('#returned_change').val(parseFloat(total_paid).toFixed(2));
var balance1 = parseFloat($('#totalamount1').val()) - parseFloat($('.tpaid').val());
var balance = parseFloat(balance1) - parseFloat(total_paid);
var balance = parseFloat(balance).toFixed(2);
$('.BalanceAmount').val(balance);
});
});
</script>
Leave a Reply