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

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

我有一个体育博彩计算器,它有几个输入字段,填写所有字段后,计算出的 table 应该会显示在下面。

显示table时,应该可以更改输入字段; table 也应该实时更改。

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

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

我目前正在使用 addEventListener“输入”变体,它只能用于一个字段。

但我想检查是否所有字段都已填写,然后 table 应该出现

嗯,首先,我认为你应该给输入字段一个唯一的 className,然后我们只检查具有 className.

的字段

例如:

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

I gave it a className called validated-field.

然后让我们使用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")
      }
    })
  })
}

我只是遍历字段并为每个字段添加一个事件侦听器。

实例: https://codepen.io/nawafscript/pen/OJjEXrW