我的jQuery代码段可以识别手动输入,但不能识别onClick输入

时间:2020-04-24 09:03:50

标签: javascript jquery

我正在尝试总结表单的字段。如果我手动插入该值,则可以正常工作。但是,当我添加数值时,请单击按钮,但事实并非如此。我相信我应该在jQuery部分中进行一些更改,但我不知道该怎么做。有人有主意吗?

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>

<script type="text/javascript">
$('form#lines-form-1 :input').change(function() {
  var tot = 0;
  $("form#lines-form-1 :input").each(function() {
    tot += Number($(this).val());    
  });
  $('#tot-qty').text(tot);
});
</script>

<script>
   function changeValueA(x){
     document.getElementById('i1').value=x.innerHTML;
    }
    function changeValueB(x){
     document.getElementById('i2').value=x.innerHTML;
    }
</script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>
    <text>Field A</text>
    <button id="80" onclick="changeValueA(this)">80</button>
    <button id="50" onclick="changeValueA(this)">50</button>
</div>

<div>
    <text>Field B</text>
    <button id="80" onclick="changeValueB(this)">80</button>
    <button id="50" onclick="changeValueB(this)">50</button>
</div>


<form id="lines-form-1">
  <label>Field A</label>
  <input type="text" id="i1" name="i1">
  <br>
  <label>Field B</label>
  <input type="text" id="i2" name="i2">
  <br>
</form>

<div id="tot-qty">0</div>

1 个答案:

答案 0 :(得分:1)

问题是因为通过代码手动更改input的值不会引发任何事件。因此,您创建的用于更新总数的change事件监听器永远不会触发。要解决此问题,您可以在更新值后手动trigger()事件。

还请注意,使用unobtruisve事件处理程序而不是内联事件处理程序是一种很好的做法。由于您已经在页面中包含了jQuery,因此您也可以坚持使用它。试试这个:

$('button').on('click', function() {
  let value = this.value;
  $($(this).data('target')).val(value).trigger('input');
});

$('.field').on('input', function() {
  let tot = 0;
  $("form#lines-form-1 :input").each((i, el) => tot += parseInt(el.value || 0, 10));
  $('#tot-qty').text(tot);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

<div>
  <text>Field A</text>
  <button type="button" id="80" data-target="#i1" value="80">80</button>
  <button type="button" id="50" data-target="#i1" value="50">50</button>
</div>

<div>
  <text>Field B</text>
  <button type="button" id="80" data-target="#i2" value="80">80</button>
  <button type="button" id="50" data-target="#i2" value="50">50</button>
</div>


<form id="lines-form-1">
  <label>Field A</label>
  <input type="text" class="field" id="i1" name="i1"><br>

  <label>Field B</label>
  <input type="text" class="field" id="i2" name="i2"><br>
</form>

<div id="tot-qty">0</div>