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?
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?
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.
}
});
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.