[英]Javascript/HTML DOM: How do I check if text user input equals to string in if statement
I am trying to check in my if statement if the text the user inputs from my html form equals to the string I indicate when submit is clicked.如果用户从我的 html 表单输入的文本等于我在单击提交时指示的字符串,我正在尝试检查我的 if 语句。 I tried using regular expressions to check if the text is a string, but not sure if done properly.
我尝试使用正则表达式来检查文本是否为字符串,但不确定是否正确完成。 Both if statements end up going straight to the "else alert()" when submit is clicked.
当单击提交时,两个 if 语句最终都会直接进入“else alert()”。
document.addEventListener('DOMContentLoaded', () => { const squares = document.querySelectorAll('.grid div') const result = document.querySelector('#result') const displayCurrentPlayer = document.querySelector('#current-player') let currentPlayer = 1 let colorSubmit = document.getElementById("color"); colorSubmit.addEventListener('submit', pickColor); function pickColor(square) { let colorStatus = isColorString(this.player1.value) //let x = document.getElementById("player1"); //var x = document.getElementById("player1").value; if (colorStatus === "red") { square.classList.add('player-red') } else if (colorStatus === "yellow") { square.classList.add('player-yellow') } else alert('pick "red" or "yellow"') let colorStatus2 = isColor2String(this.player2.value) //let y = document.getElementById("player2"); //var y = document.getElementById("player2").value; if (colorStatus2 === "blue") { square.classList.add('player-blue') } else if (colorStatus2 === "black") { square.classList.add('player-black') } else alert('pick "blue" or "black"') } function isColorString(player1) { const re = new RegExp('[az]+'); return re.test(player1); } function isColor2String(player2) { const re = new RegExp('[az]+'); return re.test(player2); }
<form id="color"> <label for="player1">Player 1 Color:</label> <input type="text" id="player1" name="player1"><br><br> <label for="player2">Player 2 Color:</label> <input type="text" id="player2" name="player2"><br><br> <input type="submit" value="Submit"> </form>
Using double equal instead of triple equal may solve your problem.使用双等号而不是三等号可以解决您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.