Home > Web Front-end > JS Tutorial > How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?

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

Patricia Arquette
Release: 2024-12-20 08:57:11
Original
907 people have browsed it

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

Trigger Button Click from Text Box Enter Key with JavaScript

To trigger a button's click event when the Enter key is pressed inside a specific text box, leverage the following jQuery code:

$("#id_of_textbox").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#id_of_button").click();
    }
});
Copy after login

Here's how it works:

  • $("#id_of_textbox"): Selects the text box element by its ID.
  • .keyup(function(event)): Registers a keyup event listener on the text box.
  • event.keyCode === 13: Checks if the key code pressed is 13, which corresponds to the Enter key.
  • $("#id_of_button").click(): Triggers the click event on the button element with the specified ID.

For example, consider the following HTML:

<input type="text">
Copy after login

To trigger the "Search" button click when Enter is pressed in the "txtSearch" text box, use this jQuery code:

$("#txtSearch").keyup(function(event) {
    if (event.keyCode === 13) {
        $("#btnSearch").click();
    }
});
Copy after login

The above is the detailed content of How to Trigger a Button Click with the Enter Key in a Text Box using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template