Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
238 views
Welcome To Ask or Share your Answers For Others

1 Answer

$("#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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...