15

I am calling a function on button click code is given blow:

<input type="button" value="Search" id="go" />

$("#go").click(function ()
{
...
});

now I catch if user hit enter key from keyboard by this function:

$("#s").keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    }
});

but how could I call

$("#go").click(function ()
    {
    ...
    });

both if user hits enter key & on click GO button?

PHP Ferrari
  • 15,754
  • 27
  • 83
  • 149

5 Answers5

30

Trigger the click handler explicitly:

$("#s").keypress(function(e) {
    if(e.which == 13) {
        alert('You pressed enter!');
    $("#go").click();
    }
});
Barmar
  • 741,623
  • 53
  • 500
  • 612
3

you can use keyup event :

$("#s").keyup(function(e) {
    if (e.which == 13) {
        $("#go").click();
    }
});
csharp
  • 59
  • 4
3

Try this one:

     $("#s").keypress(function(e) {

         if(e.which == 13) {
             e.preventDefault();
             $("#go").click();
          }
    });

Fiddle Demo

karthick
  • 5,998
  • 12
  • 52
  • 90
0

Use both click event and mouse event: I affraid, you have not mention textbox there, so I suppose you do both on button.

$("#go").keypress(function(e) {

  //Event.which == 1 mouse click left and event. which == 13 is enter key.
   if(e.which == 13 || e.which == 1 ) {
      alert('You pressed enter or clicked left mouse');
   }

});

Pir Abdul
  • 2,274
  • 1
  • 26
  • 35
0
   $(document).on("keyup", "#s", function (e) {

      if (e.which == 13) // the enter key ascii code
        {
         alert('You pressed enter!');

         $(document).on("click", "#go", function (e) {
             alert('button clicked!');
          }
        }
        
  });