How to pass text input to a click handler with JavaScript?

Sometimes, we want to pass text input to a click handler with JavaScript.

In this article, we’ll look at how to pass text input to a click handler with JavaScript.

How to pass text input to a click handler with JavaScript?

To pass text input to a click handler with JavaScript, we can select it and reference it in the click handler.

For instance, we write:

<form>
  <input type="text" name="name" />
  <input type="button" value='submit' />
</form>

to add a form with a text and button input.

Then we write:

const button = document.querySelector('input[type="button"]')
const input = document.querySelector('input[type="text"]')

button.onclick = () => {
  console.log(input.value)
}

to select the button and the text input with querySelector.

Then we set button.onclick to a function that logs the input.value property which has the text input’s value.

Conclusion

To pass text input to a click handler with JavaScript, we can select it and reference it in the click handler.