Fire event on click and enter

I have a search box on my site. Currently, users must click the submit button next to the mail search box in jQuery. I would like users to also press enter to search. How can i do this?

Jquery:

$('document').ready(function(){ $('#searchButton').click(function(){ var search = $('#usersSearch').val(); $.post('../searchusers.php',{search: search},function(response){ $('#userSearchResultsTable').html(response); }); }); }); 

HTML:

 <input type='text' id='usersSearch' /><input type='button' id='searchButton' value='search' /> 
+54
jquery jquery-selectors
Feb 05 '12 at 3:19
source share
6 answers

Use the keypress event in the usersSearch text box and find the Enter button. If you press the "Enter" button, then start the event of pressing the search button, which will do the rest of the work. Try it.

 $('document').ready(function(){ $('#searchButton').click(function(){ var search = $('#usersSearch').val(); $.post('../searchusers.php',{search: search},function(response){ $('#userSearchResultsTable').html(response); }); }) $('#usersSearch').keypress(function(e){ if(e.which == 13){//Enter key pressed $('#searchButton').click();//Trigger search button click event } }); }); 

Demo

+80
Feb 05 '12 at 3:22
source share

You call both event listeners with .on() , then use if inside the function:

 $(function(){ $('#searchButton').on('keypress click', function(e){ var search = $('#usersSearch').val(); if (e.which === 13 || e.type === 'click') { $.post('../searchusers.php', {search: search}, function (response) { $('#userSearchResultsTable').html(response); }); } }); }); 
+38
Dec 21 '13 at 20:25
source share

Something like this will work

 $('#usersSearch').keypress(function(ev){ if (ev.which === 13) $('#searchButton').click(); }); 
+5
Feb 05 '12 at 3:22
source share
 $('#form').keydown(function(e){ if (e.keyCode === 13) { // If Enter key pressed $(this).trigger('submit'); } }); 
+2
Feb 05 '12 at 3:23
source share
 $('#usersSearch').keyup(function() { // handle keyup event on search input field var key = e.which || e.keyCode; // store browser agnostic keycode if(key == 13) $(this).closest('form').submit(); // submit parent form } 
+1
Feb 05 '12 at 3:23
source share

Take a look at the keypress function .

I believe the enter key is 13 , so you need something like:

 $('#searchButton').keypress(function(e){ if(e.which == 13){ //Enter is key 13 //Do something } }); 
0
Feb 05 '12 at 3:23
source share



All Articles