Reputation: 109
I have a jquery code which calculates the total amount.
$("#quantity").on("change keyup paste", function() {
var quantity = $(this).val();
//$('#display').text(quantity);
})
$("#buy").on("change keyup paste", function() {
var buy = $(this).val();
})
var total_amnt = (((quantity * buy) * 5) / 100) + (quantity * buy);
$('#tot_amnt_display').text(total_amnt);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr style="text-align: center;">
<td>Quantity</td>
<td>Buy</td>
</tr>
<tr>
<td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
<td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-dark">
<tbody>
<tr>
<td>Total Amount</td>
<td><span id="tot_amnt_display"></span></td>
</tr>
</tbody>
</table>
In the above code's result, it just shows NaN.
On Page Load On Entering Values in the Input Box!
Upvotes: 0
Views: 39
Reputation: 68933
The default type of the value is of type string, you should convert the value to number. Also you do not need multiple event handler, simply pass the ids separated by comma.
Try the following way:
$("#quantity, #buy").on("change keyup paste", function() {
var quantity = Number($('#quantity').val());
var buy = Number($("#buy").val());
var total_amnt = (((quantity * buy) * 5) / 100) + (quantity * buy);
$('#tot_amnt_display').text(total_amnt);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<table class="table">
<tbody>
<tr style="text-align: center;">
<td>Quantity</td>
<td>Buy</td>
</tr>
<tr>
<td><input type="number" class="form-control" id="quantity" placeholder="Quantity" name="quantity"></td>
<td><input type="number" class="form-control" id="buy" placeholder="Buy Amount" name="buy"></td>
</tr>
</tbody>
</table>
<table class="table table-bordered table-dark">
<tbody>
<tr>
<td>Total Amount</td>
<td><span id="tot_amnt_display"></span></td>
</tr>
</tbody>
</table>
Upvotes: 1