簡體   English   中英

檢查是否所有輸入字段都填寫完畢,然后調用函數js

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

我有一個體育博彩計算器,它有幾個輸入字段,一旦所有字段都填寫完畢,計算表應顯示在下方。

顯示表格時,應該可以更改輸入字段; 表格也應該實時變化。

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

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

我目前正在使用 addEventListener“輸入”變體,這只能用於一個字段。

但是我想檢查所有字段是否都填寫完畢,然后表格應該出現

嗯,首先,我認為您應該給輸入字段一個唯一的className ,然后我們將檢查具有該className的字段。

例如:

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

我給了它一個名為validated-field的 className 。

然后讓我們使用 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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM