Saturday, October 20, 2018

jquery - 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:





Answer



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


No comments:

Post a Comment

plot explanation - Why did Peaches' mom hang on the tree? - Movies & TV

In the middle of the movie Ice Age: Continental Drift Peaches' mom asked Peaches to go to sleep. Then, she hung on the tree. This parti...