Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
183
rated 0 times [  189] [ 6]  / answers: 1 / hits: 30667  / 9 Years ago, sat, march 28, 2015, 12:00:00

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>

More From » html

 Answers
31

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/


[#67275] Thursday, March 26, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
emerymariamm

Total Points: 276
Total Questions: 97
Total Answers: 99

Location: Comoros
Member since Sun, Dec 13, 2020
4 Years ago
;