Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

315
Vistas
¿Por qué el campo de texto se llena al principio, pero no cuando presiono mi botón?

Estoy tratando de poner el resultado de una función simple en un campo de texto HTML después de presionar un botón.

El valor se completa correctamente cuando se inicia la aplicación, pero no hace nada cuando hago clic en el botón.

Esto es lo que tengo hasta ahora...

 function machToMph(mach) { var mph = mach * 767.269148; return mph; } // gathering information from HTML elements function onClickMethod() { var mach = document.getElementById("machs").value; //I cant exactly figure out what is going wrong here, or if im missing anything var mph = machToMph(mach); var result = mph; document.getElementById("mph").value = result } function init() { var button1 = document.getElementById("btn"); button1.addEventListener("click", onClickMethod()); } window.addEventListener("load", init);
 <input id='machs' type='text' value='10' /> <button id='btn'>Click me</button> <input id='mph' type='text' />

¿Qué estoy haciendo mal?

about 4 years ago · Santiago Gelvez
1 Respuestas
Responde la pregunta

0

La siguiente línea es incorrecta:

 button1.addEventListener("click", onClickMethod());

Está agregando el resultado de la función onClickMethod como oyente en lugar de la función en sí.

Esto es lo que realmente quieres:

 button1.addEventListener("click", onClickMethod);

Si también desea que el valor se complete previamente, agregue esta línea también:

 onClickMethod();

Manifestación

 function machToMph(mach) { var mph = mach * 767.269148; return mph; } // gathering information from HTML elements function onClickMethod() { var mach = document.getElementById("machs").value; //I cant exactly figure out what is going wrong here, or if im missing anything var mph = machToMph(mach); var result = mph; document.getElementById("mph").value = result } function init() { var button1 = document.getElementById("btn"); button1.addEventListener("click", onClickMethod); onClickMethod(); } window.addEventListener("load", init);
 <input id='machs' type='text' value='10' /> <button id='btn'>Click me</button> <input id='mph' type='text' />

about 4 years ago · Santiago Gelvez 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 Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda