Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

314
Visualizações
¿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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda