简体   繁体   中英

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> 

Three issues:

  • getElementById is an object, however, what you really want is to call that function as follow getElementById(...) .
  • .innerHTML returns the HTML rather than the entered value.
  • You have to compare against an empty value rather than null (Use the function .trim() ).

Recommendation: Use the function .addEventListener() to bind the click event.

 <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;
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM