0

I want to add event-handlers to my textbox input element for Enter and Escape keypressed.

Is there a quick way to attach an event-handler on Enter or ESC keypressed with jQuery?

Bill the Lizard
  • 398,270
  • 210
  • 566
  • 880
pencilCake
  • 51,323
  • 85
  • 226
  • 363
  • You do realise that pressing ENTER on a form textbox submits the form? – Robert Koritnik Mar 21 '11 at 13:34
  • No, it will call a webservice. – pencilCake Mar 21 '11 at 13:35
  • Nevertheless when a user will press the ENTER and if that is within a FORM (that you override its default submit with an Ajax request) it will fire `submit` event (whether that be normal or Ajax request if it's overridden). But if you're not using FORM then you don't have to worry about this. – Robert Koritnik Mar 21 '11 at 13:37
  • @Bill the Lizard: I'm not so sure that this is a duplicate of the referenced question. Because AFAIK he's asking about the **quickest way to attack keyboard events** to inputs and not **how to attach them to work** (hence I'm voting for reopening the question). – Robert Koritnik Mar 21 '11 at 13:56
  • 1
    @Robert: On second look, I agree with you. Thanks for the second opinion. – Bill the Lizard Mar 21 '11 at 14:08

2 Answers2

4

The following should do what you need:

        $("$#textboxName").keyup(function(event)
        {
            if(event.keyCode == 13) 
            {
                //Enter keypress event.
            }
            if(event.keyCode == 27)
            {
                //Escape keypress event.
            }
        });

or if you want to hit either event, you would just need an or:

       $("$#textboxName").keyup(function(event)
            {
                if(event.keyCode == 13 || event.keyCode == 27) 
                {
                    //Enter or Escape keypress event.
                }
        });
Rion Williams
  • 74,820
  • 37
  • 200
  • 327
0

The page-by-page reusable way with a jQuery plugin

To make things a bit more generic and reusable across pages, you could write a jQuery plugin called handleKey (code not final and may contain bugs):

(function($){
    $.fn.extend({
        handleKey: function(keyCode, handler) {
            if ($.isFunction(handler))
            {
                this.keyup((function(k, h){
                    return function(evt){
                        if (evt.keyCode == k)
                        {
                            h(evt);
                        }
                    };
                }
                })(keyCode, handler));
            }
        }
    });
})(jQuery);

This can be even further customized to accept a string for keyCode that would be a comma separated string to handle multiple keys with the same handler.

Usage would be:

$("input#Username").handleKey(13, function(evt){
    // your functionality
});

I'd put the plugin in my custom plugins javascript file and add reference to those pages that need it. Voila.

Robert Koritnik
  • 103,639
  • 52
  • 277
  • 404