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
: 109 At:- 9/22/2018 8:03:47 AM
jQuery Javascript trigger button click on enter key jquery






1 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





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