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

<label>Search:
 <input type="search" class="form-control input-sm" placeholder="" id="SearchInput">
</label>
<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
0
: 6418 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) {
        $("#myButton").click();
    }
});

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

OR using Javascript

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

input.addEventListener("keyup", function(event) {
    event.preventDefault();
    if (event.keyCode === 13) {
        document.getElementById("MainSearch").click();
    }
});

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.

2
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.

$('#YourButton').keydown(function(event){ 
    var keyCode = (event.keyCode ? event.keyCode : event.which);   
    if (keyCode == 13) {
        // enter is clicked do something
    }
});
0
At:- 8/4/2021 4:34:51 PM






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

Full Name *

Email *




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