Subtract Two Numbers In HTML/JavaScript -


i trying subtract 2 numbers html input form , populate result input field using javascript. unfortunately new javascript please kind point me in right direction. here's 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 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, you'll need wrap code in function, , call every time input fields 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, make sure numbers (i getting weird result when 1 of them empty), add code make sure values numeric:

function updatedue() {      var total = parseint(document.getelementbyid("totalval").value);     var val2 = parseint(document.getelementbyid("inideposit").value);      // make sure numbers     if (!total) { total = 0; }     if (!val2) { val2 = 0; }      var ansd = document.getelementbyid("remainingval");     ansd.value = total - val2; } 

you can see on jsfiddle: http://jsfiddle.net/sbu00cu2/


Comments

Popular posts from this blog

google chrome - Developer tools - How to inspect the elements which are added momentarily (by JQuery)? -

angularjs - Showing an empty as first option in select tag -

php - Cloud9 cloud IDE and CakePHP -