Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trigger an event on `click` and `enter`

I have a searchbox on my site that. Currently, users must click the submit button next to the box to search via jquery's post. I would like to let users 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' /> 
like image 627
kirby Avatar asked Feb 05 '12 03:02

kirby


People also ask

How do you make input submit on enter?

Enter = SubmitIf you have focus in the textbox and hit enter, the form will be submitted automatically. This behavior is consistent across all browsers and is known as implicit submission.

Which of the following event is triggered whenever the user presses Enter key while editing any input field in the form?

The keyup event occurs when a keyboard key is released.


2 Answers

Use keypress event on usersSearch textbox and look for Enter button. If enter button is pressed then trigger the search button click event which will do the rest of work. Try this.

$('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

like image 106
ShankarSangoli Avatar answered Oct 15 '22 13:10

ShankarSangoli


You call both event listeners using .on() then use a 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);       });     }   }); }); 
like image 28
Gustavo Rodrigues Avatar answered Oct 15 '22 15:10

Gustavo Rodrigues