Reputation:
$('#enter').click(function (){
var query = $('#search').val();
$('body').removeHighlight().highlight(query);
});
Above is the code I use for an on page instant search. How can I add an event listener so that when I hit enter it automatically triggers the .click() function as soon as I hit enter so the user doesn't have to manually have to click on the #enter element. Also if I hit enter it can't affect the value of search field. It'd be helpful if the code was in jQuery.
Upvotes: 2
Views: 151
Reputation: 79830
I assume that you meant Enter press from search
textbox. Try below and let me know if this is something you want,
$('#search').keydown(function (e) {
if (e.which == 13) {
e.preventDefault();
$('#enter').click();
}
});
Try changing your query function like below,
$('#enter').click(function (){
var query = $('#search').val();
if ($.trim(query) != '') {
$('body').removeHighlight().highlight(query);
}
});
Upvotes: 0
Reputation: 633
You could use the keypress event on jquery to trigger the event.
$('#enter').keypress(function (e){
var code = (e.keyCode ? e.keyCode : e.which);
if(code == 13) {
var query = $('#search').val();
$('body').removeHighlight().highlight(query);
}
});
Upvotes: 3
Reputation: 9092
Like I said in the comment, you can use keypress like this
$('#search').keypress(function(event) {
if ( event.which == 13 ) {
$('#enter').trigger('click');
}
})
Upvotes: 0