简体   繁体   English

检查是否所有输入字段都填写完毕,然后调用函数js

[英]Check whether all input fields are filled out, then call function js

I have a sports betting calculator, this has several input fields, as soon as all fields are filled out, the calculated table should be displayed below.我有一个体育博彩计算器,它有几个输入字段,一旦所有字段都填写完毕,计算表应显示在下方。

When the table is displayed, it should be possible to change the input fields;显示表格时,应该可以更改输入字段; the table should then also change in real time.表格也应该实时变化。

HTML: <input type="number" class ="form-control input-lg" id="quoteBack"> HTML: <input type="number" class ="form-control input-lg" id="quoteBack">

JS: document.getElementById("quoteBack").addEventListener("input", function() {}); JS: document.getElementById("quoteBack").addEventListener("input", function() {});

I am currently using the addEventListener "input" variant, this can only be used on one field.我目前正在使用 addEventListener“输入”变体,这只能用于一个字段。

But I want to check that all fields are filled out, then the table should appear但是我想检查所有字段是否都填写完毕,然后表格应该出现

Hmm, first of all, I think you should give the input field a unique className , then we just gonna check the fields that have that className .嗯,首先,我认为您应该给输入字段一个唯一的className ,然后我们将检查具有该className的字段。

For example:例如:

<input type="number" class ="form-control input-lg validated-field" id="quoteBack">

I gave it a className called validated-field .我给了它一个名为validated-field的 className 。

Then let's check those fields using JavaScript:然后让我们使用 JavaScript 检查这些字段:

// Get fields by className
var fields = document.getElementsByClassName("validated-field")

// Array.from will convert the HTMLCollection to Native Array.
if (Array.from(fields).length > 0) {
  // Loop
  Array.from(fields).forEach(field => {
    // Add Event for each field.
    field.addEventListener("input", function(e) {
      console.log(e.target.value)
      if (!e.target.value) {
        e.target.classList.add("not-valid")
      } else {
        e.target.classList.remove("not-valid")
      }
    })
  })
}

I just loop through the fields and add an event listener for each field.我只是遍历字段并为每个字段添加一个事件侦听器。

Live Example: https://codepen.io/nawafscript/pen/OJjEXrW现场示例: https : //codepen.io/nawafscript/pen/OJjEXrW

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM