动态更新输入值并在动态输入更改后更新另一个元素

时间:2018-11-12 00:24:46

标签: jquery forms events input dynamically-generated

下面是我针对遇到的问题创建的示例HTML和JS。我有一个包含三个输入的表格。前两个输入的值将决定第三个输入的值。我还希望所有三个输入的值都显示在表单外部的<p>标记中。我已经能够正确地更新窗体外的前两个<p>标记,并且我能够正确地更新第三个输入值。但是,当第三个输入值已动态更改时,我无法获取第三个<p>标记。

这里是问题的Codepen

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 个答案:

答案 0 :(得分:1)

  1. 将值加到和上时手动调用change事件

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>