You can just make "perform the action" a separate function and then
call it from the two events

function performAction(){
 //do stuff
}

$("#text_input").keyup(function(e)
   {
      // Checks if the Enter key was entered
      if(e.keyCode == 13)
      {
         performAction();
      }
   });

$("#push_button").click(performAction);





On Mar 3, 5:40 pm, James <james.gp....@gmail.com> wrote:
> Something like:
>
> $(document).ready(function()
> {
>    $("#text_input").keyup(function(e)
>    {
>      checkKey(e);
>    });
>
> });
>
> function checkKey(e) {
> // Checks if the Enter key was entered
>       if(e.keyCode == 13)
>       {
>          // perform the action
>       }
>
> };
>
> On Mar 3, 9:26 am, Thierry <lamthie...@gmail.com> wrote:
>
> > I have the following piece of code which checks if a user has pressed
> > the Enter key in a text input with id="text_input" and then performs
> > some action:
>
> > $(document).ready(function()
> > {
> >    $("#text_input").keyup(function(e)
> >    {
> >       // Checks if the Enter key was entered
> >       if(e.keyCode == 13)
> >       {
> >          // perform the action
> >       }
> >    });
>
> > });
>
> > I also have a button with id="push_button" that I wish will perform
> > the same action as above when clicked.  How can I rewrite the above so
> > that I check for either of those two events and perform that one
> > action without code duplication?

Reply via email to