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?
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(); 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' />