Vincent
Vincent

Reputation: 852

How to create a two action in one function (keypress and click)

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

Answers (4)

Dane O&#39;Connor
Dane O&#39;Connor

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

  • change Function to function
  • define the Search function before your handlers

Upvotes: 1

voscausa
voscausa

Reputation: 11706

You can use .on for binding a function to multiple events.

$(' #searchbtn ').on('click keypress', function() {
// some action
});

Upvotes: 0

Kitsune
Kitsune

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

Abraham K
Abraham K

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

Related Questions