Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Onsubmit function refreshes page

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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> 
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading