【问题标题】:Getting the sum of all number inputs on each keypress重置所有其他输入如果值达到高于指定值 javascript
【发布时间】:2022-01-04 04:57:14
【问题描述】:

所以我在 HTML 中有 3 个输入框

<input type="number" id="geoOnePercentage" placeholder="Geo 1 Percentage" />
<input type="number" id="geoTwoPercentage" placeholder="Geo 2 Percentage" />
<input type="number" id="geoThreePercentage" placeholder="Geo 3 Percentage" />

我想要做的是,当用户在这些输入框中输入内容时,请继续检查如果他们的总数超过 100 的值,一旦用户输入一个使总数超过 100 的值,就会重置表单。

例如,用户在第一个输入框中输入50,就可以了。 然后用户在下一个输入框中输入40,也可以, BUT THEN 如果用户输入了一个值,例如15,这使得所有输入框的值总和超过,则重置所有3个输入框的值。

但是,我不知道该怎么做。我对 JavaScript 中的 onkeydown 事件有所了解,但它没有按预期工作。

如果有人能说明如何做到这一点,我将不胜感激。

【问题讨论】:

    标签: javascript html validation input


    【解决方案1】:

    let inputs = [...document.querySelectorAll('input[type="number"]')];
    
    inputs.forEach(inp => inp.addEventListener('input', function() {
      const total = inputs.reduce((acc, inp) => acc + Number(inp.value), 0);
      if (total > 100) {
        inputs.forEach(inp => inp.value = '');
      }
    }))
    <input type="number" id="geoOnePercentage" placeholder="Geo 1 Percentage" />
    <input type="number" id="geoTwoPercentage" placeholder="Geo 2 Percentage" />
    <input type="number" id="geoThreePercentage" placeholder="Geo 3 Percentage" />

    【讨论】:

      猜你喜欢
      • 2021-10-15
      • 1970-01-01
      • 1970-01-01
      • 2020-03-28
      • 2016-12-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-02-04
      相关资源
      最近更新 更多