0

I have been having problems lately with a page reloading during form submission. I finally found out that the page reloads when I submit the form with EventListener, but it doesn't reload with onclick form submission. The code below is how I tested that. Can someone please explain to me why?

<html>
  <head>
    <title>Reload Page Test</title>
    <script>
      document.addEventListener("DOMContentLoaded", function () {

        document.querySelector("#asubmit").addEventListener("click", test);

        document.querySelector("#bsubmit").onclick = test;
        
        function test(){
          const name = document.getElementById("name").value;
          const age = document.getElementById("num").value;
          document.getElementById(
            "result"
          ).innerHTML = `${name} is ${age}years old.`;
          return false;
        };

      });
    </script>
  </head>
  <body>

    <div>
      <form>
        <input type="text" id="name" />
        <input type="number" id="num" />
        <input type="submit" id="asubmit" value="Event Listener Submit"/>
        <input type="submit" id="bsubmit" value="On Click Submit">
      </form>`enter code here`
    </div>
    <div id="result"></div>

  </body>
</html>
  • [What's the effect of adding 'return false' to a click event listener?](https://stackoverflow.com/questions/128923/whats-the-effect-of-adding-return-false-to-a-click-event-listener) – Andreas Mar 22 '22 at 09:38
  • [event.preventDefault() vs. return false (no jQuery)](https://stackoverflow.com/questions/18971284/event-preventdefault-vs-return-false-no-jquery) – Andreas Mar 22 '22 at 09:39
  • Thanks for the further explanation links. – Naing Lin Maung Mar 22 '22 at 09:49

1 Answers1

2

Returning false from an onclick function will prevent the default behaviour.

The return value of an event listener callback is meaningless.

Use event.preventDefault() instead.

function test(event) {
    // ...
    event.preventDefault();
}
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335