0

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?

John Slegers
  • 45,213
  • 22
  • 199
  • 169

1 Answers1

1

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' />
John Slegers
  • 45,213
  • 22
  • 199
  • 169