views:

49

answers:

2

I'm trying to run a method when the enter key has been pressed. This method is already being used by a button. Basically, when the user fills in a text field and clicks a submit button they get a lightbox. What I want to do is run this same action, but when the enter key has been pressed. Ive looked into using .keypress but I can only find examples where the form tag is a standard html form tag and not a asp.net form tag. I think at the moment the form is responding only to the .net controls on the page and I cant override this with the jquery method. Any ideas?

A: 

You can bind a keypress event to the document and trigger() the handler on your button.

$(document).bind('keypress', function(e){
   if(e.which === 13) { // return
      $('#buttonid').trigger('click');
   }
});

This would fire whenever you press the return key on your site. You probably want it only to happen if someone uses return in your input form. You would just need to change the selector from document to any kind of selector that matches your control.

Ref.: .trigger()

jAndy
Dang, Andy, I feel like I'm racing you all the time. When do you sleep? =)
mkoistinen
@mkoistinen: I've never heard about that, tell me more about that "sleep" thingy :p
jAndy
Thanks a lot Andy!
PhilipP
A: 
$(document).keydown(function(e) {
   // test for the enter key
   if (e.keyCode == 13) {
      // Do your function
      myFunction();
   }
});
mkoistinen