Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

311
Views
¿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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!