zzz zzz - 1 month ago 7
HTML Question

How to calculate sum on change?

How to go about calculating the sum of two fields on change?

My HTML

<div class="field">
<label for="field1">F1:</label>
<input type="number" name="field1" min="0" placeholder="0" Title="Only positive numbers" required></div>
<div class="field">
<label for="field2">Field2:</label>
<input type="number" name="field2" disabled>
</div>


And i got this but unsure on how this works/how to get it to work..

<script> $(".input").on("change", function(){
var ret = Number($(".field1").val()) + Number($(".field2").val());
$("#field3").val(ret);


Is there an easier way to do this?

Answer

Any change in input will trigger the .on()'s callback function. Inside get the value of field1and field2 and parse it into int as they will be a string. Add them both and insert into field3

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="field">
  <label for="field1">F1:</label>
  <input type="number" id="field1" min="0" placeholder="0" Title="Only positive numbers" required/>
</div>
<div class="field">
  <label for="field2">Field2:</label>
  <input type="number" id="field2"/>
</div>

<input type="number" disabled id="field3"></input>

<script>
  $("input").on("change", function() {
    var ret = parseInt($("#field1").val()) + parseInt($("#field2").val() || '0')
    $("#field3").val(ret);
  })
</script>