• Empleos
  • Sobre nosotros
  • profesionales
    • Inicio
    • Empleos
    • Cursos y retos
  • empresas
    • Inicio
    • Publicar vacante
    • Nuestro proceso
    • Precios
    • Evaluaciones
    • Nómina
    • Blog
    • Comercial
    • Calculadora de salario

0

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

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Nuestro proceso Comercial
Legal
Términos y condiciones Política de privacidad
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recomiéndame algunas ofertas
Necesito ayuda