0

Below is the sample HTML and JS that I created for the problem that I am having. I have a form that has three inputs. The value from the first two inputs will dictate the value of the third. I also want the values of all three inputs to display in <p> tags outside of the form. I have been able to update the first two <p> tags outside the form correctly, and I have been able to update the third input value correctly. However, I cannot get the third <p> tag to update when the third input value has dynamically changed.

Here is a Codepen for the problem.

HTML

<form>
  <input id="one" type="number" class="sumVari" name="a"> 
  <input id="two" type="number" class="sumVari" name="b">
  <input id="three" type="number" name="sum" placeholder="sum of a & b">
</form>
<div id="displayValues">
  <p>The value of a is: <span id="a"></span> </p>
  <p>The value of a is: <span id="b"></span></p>
  <p>The value of the sum is: <span id="sum"></span></p>
</div>

JS

let one = $('#one');
let two = $('#two');
let three = $('#three');

$('form').on('change', 'input', function() {
  let target = $(this);
  let attrName = target.attr('name');

  $('#'+attrName).text(target.val());
});

function sum(a,b) {
  return a+b;
}

$('.sumVari').each(function(){
  $(this).change(function(){
    if(one.val() != '' && two.val() != '') {
      three.val(sum(one.val(), two.val()));
    }
  });
});

1 Answer 1

2
  1. Call the change event manually when putting value on the sum

let one = $('#one');
let two = $('#two');
let three = $('#three');

$('form').on('change', 'input', function() {
  let target = $(this);
  let attrName = target.attr('name');

  $('#' + attrName).text(target.val());
});

function sum(a, b) {
  return a + b;
}

$('.sumVari').each(function() {
  $(this).change(function() {
    if (one.val() != '' && two.val() != '') {
      three.val(sum(one.val(), two.val())).change();//call the change event manually here on the sum input so that the change function will run on the sum input
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <input id="one" type="number" class="sumVari" name="a">
  <input id="two" type="number" class="sumVari" name="b">
  <input id="three" type="number" name="sum" placeholder="sum of a & b">
</form>
<div id="displayValues">
  <p>The value of a is: <span id="a"></span> </p>
  <p>The value of a is: <span id="b"></span></p>
  <p>The value of the sum is: <span id="sum"></span></p>
</div>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.