I try to auto calculate html input values to show total values in input .
here is my input form
<div class="col-sm-4">
<form>
<div class="mb-3">
<label for="">Price</label>
<input type="text" id="price" required class="price form-control">
</div>
<div class="mb-3">
<label for="">Amount</label>
<input type="text" id="amount" required class="amount form-control">
</div>
<div class="mb-3">
<label for="">Total</label>
<input type="text" id="total" required class="total form-control">
</div>
<button type="submit" class="btn btn-primary marketbuy">Buy </button>
</form>
</div>
I want total value automatically when enter amount value and price value into input form.
example
price is 3
amount is 5
total is 15
when I enter 3 and 5
total input show automatically 15
var p1 = $('#price').val();
var p2 = $('#amount').val();
$('#total').val(p1*p2);
console.log()
this code not show directly in total input but show when reload.
How can get by jquery.
2
Answers
The issue is because your code is only running when the page loads. You need to hook event handlers to the
input
fields so that the total also gets calculated as the user enters values.Below is a working example of how to do this. Note that the common logic which updates the
total
field is extracted to its own function which is called when the page loads and also when a field is updated. Also note that I added therequired
attribute to thetotal
field so that the user cannot update it – it can only be set programmatically.