Reputation: 852
I have a function that on click of a button the function in jquery will run. i also want to add another action , the "Enter" key. Here is my code
<input type=text id=search> <button id=searchbtn>Search</button>
and my jquery is only for the button. how can i also add the enter key? on the input text?
$(' #searchbtn ').click(function(){
some action
}
onkeypress? how? click and keypress in one function?
EDIT: I've tried the following but it doesn't appear to work:
$(document).ready(function(){
///search this table
$(' #search ').click(function(){
Search();
});
$( '#emp_search ').keypress(function(e){
if(e.which == 13) {
Search();
}
}
function Search(){ alert('test');
}
Upvotes: 0
Views: 269
Reputation: 77298
Instead of requiring 'one function', instead call the same function with two handlers:
$(' #searchbtn ').click(function(){
someAction();
}
$(' #searchbtn ').keypress(function(){
someAction();
}
Edit: at least two things are wrong with your snippet
Function
to function
Search
function before
your handlersUpvotes: 1
Reputation: 11706
You can use .on for binding a function to multiple events.
$(' #searchbtn ').on('click keypress', function() {
// some action
});
Upvotes: 0
Reputation: 9341
Create a function for the shared code. You can pass that function directly to the click() handler (no need to wrap it in yet-another function), and for the keypress event handler, wrap it in a function that will check the key code, and conditionally call the shared function.
function sharedFunction() {
/* Some common action */
}
// Your current handler
$('#searchbtn').click(sharedFunction);
// The new handler to catch the 'enter' key.
$('#searchtext').keypress(function(event) {
if(event.keyCode == 13){
sharedFunction();
}
});
Upvotes: 0
Reputation: 634
Use for your textbox, not for button,
$(#searchtext).keypress(function(e) {
if(e.which == 13) {
//search
Search();
}
});
$(' #searchbtn ').click(function(){
Search();
}
Function Search()
{
//do anything you want
}
Upvotes: 1