簡體   English   中英

驗證 javascript 和 html 表格

[英]Validate javascript and html form

我正在做練習,但無法驗證和發送表格。

我有這個 HTML 代碼,我無法添加或修改任何內容:

</head>
  <body>
    <h1>Card game</h1>

    <p>
      <label>Displays the name of the participant</label
      ><input type="text" name="name" />
    </p>
    <p>
      <label>how many games do you want to play? </ tag
      ><input type="number" name="games" value="0" />
    </p>
    <button>PARTICIPATE!</button>


   <script type="text/javascript" src="rockPaperScissors.js"></script>
  </body>

我正在嘗試驗證表單,當我點擊參與按鈕並且不符合驗證條件時,它應該將字段變為紅色。 更正數據並驗證表單后,必須停用這些字段,以便它們無法再次寫入並保持可見。

我已經這樣做了,但我沒有達到我的目標:

function validateName() {
  const name = document.getElementsByName("name");
  const expression1 = /[A-Za-z]{3,}/;
  name.click();

  if (!expression1.test(name.value)) {
    name.classList.add("RedBackground");
    false return;
  }
  return true;
}

function validateGames() {
  games.click();
  const items = document.getElementsByName("items");
  if (games.value <= 0) {
    games.classList.add("RedBackground");
    false return;
  }
  return true;
}

// Indicate who launches the events
document
  .getElementsByTagName("button")[0]
  .addEventListener("click", validateName);

document
  .getElementsByTagName("button")[0]
  .addEventListener("click", validateGames);

問題

<input type="text" name="name" />
const name = document.getElementsByName("name");

getElementsByName返回一個集合而不是單個元素。

可能的解決方案

要獲取name屬性等於name的第一個元素,您必須獲取集合的第一個索引:

const name = document.getElementsByName("name")[0];

或返回第一個匹配元素的querySelector

const name = document.querySelector("[name=name]");

例子

 document.querySelector("button").addEventListener("click", function(){ //REM: Is everything valid? let tValid = true; //REM: Validate "name" using "querySelector" let tName = document.querySelector("[name=name]"); if(tName){ //REM: Put your logic here tName.classList.add("RedBackground"); tValid = false }; //REM: Validate "games" using "getElementsByName" let tGames = document.getElementsByName("games")[0]; if(tGames){ //REM: Put your logic here tGames.classList.add("BlueBackground"); tValid = false }; return tValid });
 .RedBackground{ background-color: crimson }.BlueBackground{ background-color: cornflowerblue }
 <h1>Card game</h1> <p> <label>Displays the name of the participant</label> <input type="text" name="name" /> </p> <p> <label>how many games do you want to play? </ tag> <input type="number" name="games" value="0" /> </p> <button>PARTICIPATE!</button>

我建議,即使可能,也不要將關鍵字名稱重用為變量name

暫無
暫無

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

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