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?
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.
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
}
});
Subscribe to our weekly Newsletter & Keep getting latest article/questions in your inbox weekly