Categories
JavaScript Answers

How to Trigger a Button Click with JavaScript on the Enter Key in a Text Box?

Spread the love

If we have a text box on our web page, we may want to trigger a button click when we press the enter key.

In this article, we’ll look at how to trigger a button click with JavaScript when an enter key is pressed in a text box.

Use the click Method

We can call the click method that’s available with HTML element node objects to click an element programmatically.

For instance, we can write the following HTML:

<input type="text" id="txtSearch"  />
<input type="button" id="btnSearch" value="Search" />

Then we can write the following JavaScript code to check for the Enter keypress and trigger a button click afterwards:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.keyCode == 13) {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

We get the 2 inputs with document.getElementById .

Then we call addEventListener on txtSearchEl with the 'keydown' string as the first argument to add an event listener for the keydown event.

Next, we pass in a callback as the 2nd argument that runs when the event is triggered.

In the callback, we check the keyCode property to see if it’s 13.

If it is, then the Enter key is pressed.

Then we get the btnSearchEl HTML element node object, which is the button below the text box, and call click on it.

The click method triggers the click programmatically.

Next, we add a click listener to the btnSearchEl element node object to do something when a button is clicked.

And so when click is called, we should see 'search button clicked' logged.

We can also check the event.key property instead of the event.keyCode property.

For instance, we can write:

const txtSearchEl = document.getElementById('txtSearch')
const btnSearchEl = document.getElementById('btnSearch')

txtSearchEl.addEventListener('keydown', (event) => {
  if (event.key === "Enter") {
    btnSearchEl.click()
  }
})

btnSearchEl.addEventListener('click', () => {
  console.log('search button clicked')
})

event.key returns a string with the name of the key we pressed, so it’s more intuitive than checking a key code.

Conclusion

We can trigger a button click after a key press by watching the keydown event with an event listener.

In the event listener, we call click on the button element object to trigger the click programmatically.

And we can attach a click event listener on the button element to do something when we click on the button.

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 *