Skip to content Skip to sidebar Skip to footer

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.

Solution 1:

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

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

$(document.body).keyup(function(ev) {
    // 13 is ENTERif (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.

Solution 2:

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 ENTERif (ev.which === 13 && /*whatever other conditions you care about*/) {
      // do something
   }
}); 

Post a Comment for "Bind Textbox To 'enter' Key"