How to trigger click on pressing Enter key inside text input using Javascript or jQuery?

How to trigger the click event on the search button, when user press enter key inside text input html, suppose this is my HTML

 <input type="search" class="form-control input-sm" placeholder="" id="SearchInput">
<button class="btn btn-primary" style="margin:0 10px" id="MainSearch">Search</button><button class="btn btn-danger">clear</button>

So, when a user clicks enter inside "#SearchInput" element, it trigger clicks on "#MainSearch" button, how can I do that using javascript or jQuery?

Asked by:- neena
: 4485 At:- 9/22/2018 8:03:47 AM
jQuery Javascript trigger button click on enter key jquery

2 Answers
profileImage Answered by:- vikas_jk

Trigger click on Enter using jQuery

$("#SearchInput").keyup(function(event) {
    if (event.keyCode === 13) {

$("#MainSearch").click(function() {
  console.log("Button clicked.");

OR using Javascript

var input = document.getElementById("SearchInput");

input.addEventListener("keyup", function(event) {
    if (event.keyCode === 13) {

OR Using inline-javascript

<input type = "text"
       id = "SearchInput" 
       onkeydown = "if (event.keyCode == 13)
                        document.getElementById('btnSearch').click()" />

<input type = "button"
       id = "MainSearch"
       value = "Search"
       onclick = "doSomething();"/>

Hope this helps.

At:- 9/24/2018 7:11:52 AM
Working as expected, I have implemented jQuery method, didn't used JS one. 0
By : neena - at :- 9/26/2018 11:12:43 AM

profileImage Answered by:- pika

keycode 13 = enter, so we can simply use the below jquery code to check if 'Enter' keyboard button is clicked.

    var keyCode = (event.keyCode ? event.keyCode : event.which);   
    if (keyCode == 13) {
        // enter is clicked do something
At:- 8/4/2021 4:34:51 PM

Login/Register to answer
Register directly by posting answer/details

Full Name *

Email *

By posting your answer you agree on privacy policy & terms of use

Subscribe Now

Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly