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

317
Vistas
Why does the text field get filled at the start, but not when I push my button?

I am trying to put the result of a simple function into an HTML text field after a button is pressed.

The value is correctly filled in when the app starts, but it doesn't do anything when I click the button.

This is what I have so far...

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' />

What am I doing wrong?

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

0

The following line is incorrect :

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

You're adding the result of the function onClickMethod as a listener instead of the function itself.

This is what you actually want :

button1.addEventListener("click", onClickMethod);

If you also want the value to be pre-filled, add this line as well :

onClickMethod();

Demo

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