Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

62
Vistas
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>
7 months ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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();
}
7 months ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos