【问题标题】:Checking if inputs fields are filled检查输入字段是否已填写
【发布时间】:2021-03-26 11:00:33
【问题描述】:

我正在尝试检查是否所有输入字段都填写在此表单中,输入是根据玩家数量创建的,所以我在 JavaScript 中动态创建了它们,我该怎么做? 这是我尝试过的

const x = localStorage.getItem('playersNum');

for (let i = 0; i < x; i++) {

    const newInput = document.createElement("INPUT");
    newInput.setAttribute("type", "text");
    newInput.setAttribute("class", "form-control");
    newInput.setAttribute("id", `player${i}`);
    newInput.setAttribute("placeholder", "Player's Name");
    const parentDiv = document.getElementById('player-list');

    parentDiv.appendChild(newInput);

    const input = document.getElementById(`player${i}`);
    const btn = document.getElementById('startGame');
    btn.addEventListener('click', function() {
        if (input === "") {
            alert('Please fill in the players names');
        }
    });

}

【问题讨论】:

  • 这里有一个问题:if (input.value === ""),但除了这个问题之外,您在控制台上还会遇到什么错误?
  • 请提供完整的代码! x 这里是什么?
  • @FabrizioCalderanlovestrees 我尝试了 input.value,现在错误不断根据玩家数量重新加载次数,我认为这是因为我在 for 循环中执行此操作。

标签: javascript html css twitter-bootstrap


【解决方案1】:

您可以尝试以下方法:

const parentDiv = document.getElementById('player-list');
for (let i = 0; i < 2; i++) {
  const newInput = document.createElement("INPUT");
  newInput.setAttribute("type", "text");
  newInput.setAttribute("class", "form-control");
  newInput.setAttribute("id", `player${i}`);
  newInput.setAttribute("placeholder", "Player's Name");

  parentDiv.appendChild(newInput);
}

//get all input elements of type text and starting id with player
const input = document.querySelectorAll("[type='text'][id^='player']");
const btn = document.getElementById('startGame');
btn.addEventListener('click', function() {
  //reset border style of all input elements
  [...input].forEach(el => el.style.border = '');
  //get all empty input elements
  let empty = [...input].filter(el => el.value.trim() == "");
  //check length
  if (empty.length) {
    //show alert
    alert('Please fill in the players names');
    //set border style to empty input elements
    empty.forEach(el => el.style.border = '1px solid red');
  }
});
<button id="startGame">Start Game</button>
<div id="player-list"></div>

【讨论】:

    【解决方案2】:

    您应该检查inputs 是否为空,并仅在创建它们之后将事件侦听器附加到开始游戏按钮:这意味着在for 循环之后。

    作为一项改进,您可以在inputs 上添加required 属性,如果它们无效(使用:invalid 伪类)检查CSS

    const x = 3; 
    
    const parentDiv = document.getElementById('player-list');
    const btn = document.getElementById('startGame');
    
    let players;
    
    for (let i = 0; i < x; i++) {
        const newInput = document.createElement("input");
        newInput.setAttribute("type", "text");
        newInput.setAttribute("required", "required");
        newInput.setAttribute("class", "form-control");
        newInput.setAttribute("id", `player${i}`);
        newInput.setAttribute("placeholder", "Player's Name");
        parentDiv.appendChild(newInput);
    }
    
    /*
     * Get all the inputs you have just injected 
     */
    players = [...document.querySelectorAll('.form-control')];
    
    /*
     * Check if there are some inputs not filled
     */ 
    btn.addEventListener('click', function() {
      if (players.some((p) => p.value === '')) {
          alert('Please fill in ALL the players names');
      }
      else {
         alert('Ok');
      }
    });
    input {
       display: block;
       margin: 1rem;
       border: 1px #ccc solid;
       padding: .25rem;
    }
    
    input:invalid {
     outline: 1px #aa0020 solid;
     outline-offset: 1px;
    }
    <div id="player-list"></div>
    
    <button id="startGame">Start Game</button>

    【讨论】:

      猜你喜欢
      • 2021-09-30
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      • 2021-02-27
      • 1970-01-01
      • 1970-01-01
      • 2014-03-01
      • 2015-11-19
      相关资源
      最近更新 更多