Home > Blockchain >  Onsubmit function refreshes page
Onsubmit function refreshes page

Time:05-03

Very basic code that I can't get to work. The onsubmit function gets called, but the page refreshes back to its original form as if it executes but then restarts the HTML. The console.log flashes but then disappears as if we've restarted the page.

I've commented out the "return false" because that seems to not be making a difference.

What silly mistake am I making? Thanks in advance.

<form method="POST" style="display: inline" onsubmit="validateAnswer()">
  <label for="answer" >Secret Word</label>
  <input id="answer" name="answer" size="15" type="text" />
  <input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3> 

 
 <script>
    function validateAnswer() {
      var y = document.getElementById("answer").value;
      console.log("y: "   y);
      if ( y == "YOU" || y == "You" || y == "you" ){
          document.getElementById("answerText").innerHTML = "Correct!"; 
          // return false;
      } else {
          document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
        // return false;
        }
    }
 </script>

CodePudding user response:

You miss action and event.preventDefault(); to prevent sending the form

    function validateAnswer(event) {
        
      var y = document.getElementById("answer").value;
      console.log("y: "   y);
      if ( y == "YOU" || y == "You" || y == "you" ){
          document.getElementById("answerText").innerHTML = "Correct!"; 
          // return false;
      } else {
          document.getElementById("answerText").innerHTML = "Sorry, that's not correct";
          event.preventDefault();
          return false;
        }
    }
<form method="POST" style="display: inline" action="https://stackoverflow.com/" onsubmit="validateAnswer(event)">
  <label for="answer" >Secret Word</label>
  <input id="answer" name="answer" size="15" type="text" />
  <input type="submit" value="Submit">
</form>
<br>
<h5 id="answerText"></h3> 

  • Related