Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bind textbox to 'enter' key

I need to bind the 'enter' key on the keyboard to a specific javascript method, but ONLY when a certain text field is in focus.

<input id="post" type="text" style="width:400px;"/>

How would I do this?

I know you can do it with forms and stuff that have a submit action, but can I just bind the 'enter' key to a specific function when this above input field is in focus?

like image 797
slandau Avatar asked May 10 '11 00:05

slandau


2 Answers

$("#post").focus(function() {
    $(this).data("hasfocus", true);
});

$("#post").blur(function() {
    $(this).data("hasfocus", false);
});

$(document.body).keyup(function(ev) {
    // 13 is ENTER
    if (ev.which === 13 && $("#post").data("hasfocus")) {
        ...
    }
});

I recommend you instead bind the the ENTER keyup event on your $("#post") input directly rather then listening for the event on the entire page.

like image 172
Raynos Avatar answered Nov 15 '22 23:11

Raynos


Just bind the onkeyup event to the input in question. You don't need to worry about checking focus at all, because by definition that input will only receive keyup events when it has focus.

I assume JQuery is OK since you included the tag in your question, so within your document ready handler do something like this:

$("#IDforyourcontrol").keyup(function(ev) {
   // 13 is ENTER
   if (ev.which === 13 && /*whatever other conditions you care about*/) {
      // do something
   }
}); 
like image 44
nnnnnn Avatar answered Nov 16 '22 00:11

nnnnnn