I am trying to subtract two numbers from an HTML Input form and populate the result into another input field using JavaScript. Unfortunately i am new to JavaScript so please be so kind to point me in the right direction. Here's my HTML code.
<div class="form-group col-lg-6">
<label for="exampleInputText">Total Price</label>
<input type="text" name="totalval" class="form-control" id="totalval">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Initial Deposit</label>
<input type="text" name="inideposit" class="form-control" id="inideposit">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Outstanding Dues</label>
<input type="text" name="remainingval" class="form-control" id="remainingval" >
</div>
Here is my JavaScript code:
<script type="text/javascript">
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
</script>
Your code works fine, so you'll just need to wrap your code in a function, and then call it every time that the input fields are modified (onchange event).
<div class="form-group col-lg-6">
<label for="exampleInputText">Total Price</label>
<input type="text" name="totalval" class="form-control" id="totalval" onchange="updateDue()">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Initial Deposit</label>
<input type="text" name="inideposit" class="form-control" id="inideposit" onchange="updateDue()">
</div>
<div class="form-group col-lg-6">
<label for="exampleInputText">Outstanding Dues</label>
<input type="text" name="remainingval" class="form-control" id="remainingval">
</div>
Finally, to make sure they are numbers (I was getting some weird result when one of them was empty), add some code to make sure the values are numeric:
function updateDue() {
var total = parseInt(document.getElementById("totalval").value);
var val2 = parseInt(document.getElementById("inideposit").value);
// to make sure that they are numbers
if (!total) { total = 0; }
if (!val2) { val2 = 0; }
var ansD = document.getElementById("remainingval");
ansD.value = total - val2;
}
You can see it on this JSFiddle: http://jsfiddle.net/sbu00cu2/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With