[英]Javascript - Nothing happens when I click this button connected to a function
So, I'm trying to validate an input field, where an input field cannot be empty. 因此,我正在尝试验证输入字段,其中输入字段不能为空。 If someone doesn't enter any text into the input field and click 'start a new game' button it should display an alert message saying you need to enter a name.
如果有人没有在输入字段中输入任何文本,然后单击“开始新游戏”按钮,它将显示一条警告消息,提示您需要输入名称。
However, my code does not display the alert message for some reason. 但是,由于某些原因,我的代码未显示警报消息。
Here's my code. 这是我的代码。
<html> <head> <title>Tic Tac Toe</title> </head> <script> function myFunction() { if (document.getElementById(“playerNameNew").innerHTML == null) { alert("Name must be filled out"); return false; } } </script> <body> <header> <h1>Tic - Tac - Toe</h1> </header> <h3>Start a new Game</h3> <input type="text" id="playerNameNew" placeholder="Enter your name" required> <button onclick="myFunction()" id="new">Start a New Game</button> </body> </html>
getElementById
is an object, however, what you really want is to call that function as follow getElementById(...)
. getElementById
是一个对象,但是,您真正想要的是按照getElementById(...)
调用该函数。 .innerHTML
returns the HTML rather than the entered value. .innerHTML
返回HTML而不是输入的值。 .trim()
). .trim()
函数)。 Recommendation: Use the function .addEventListener()
to bind the click event. 建议:使用函数
.addEventListener()
绑定click事件。
<html> <head> <title>Tic Tac Toe</title> </head> <script> function myFunction() { if (!document.getElementById("playerNameNew").value.trim()) { alert("Name must be filled out"); return false; } } </script> <body> <header> <h1>Tic - Tac - Toe</h1> </header> <h3>Start a new Game</h3> <input type="text" id="playerNameNew" placeholder="Enter your name" required> <button onclick="myFunction()" id="new">Start a New Game</button> </body> </html>
if (document.getElementById("playerNameNew").value == '') {
alert("Name must be filled out");
return false;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.