【问题标题】:Update input value dynamically & update another element after dynamic input change动态更新输入值并在动态输入更改后更新另一个元素
【发布时间】:2018-11-12 00:24:46
【问题描述】:

下面是我为遇到的问题创建的示例 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()));
    }
  });
});

【问题讨论】:

    标签: jquery forms events input dynamically-generated


    【解决方案1】:
    1. 对总和赋值时手动调用更改事件

    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>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-08-30
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 1970-01-01
      • 2020-01-28
      相关资源
      最近更新 更多