Categories
JavaScript Answers

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

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *