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

Why EventListener reloads the page and onclick does not?

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>

>Solution :

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

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