Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
31
rated 0 times [  35] [ 4]  / answers: 1 / hits: 20057  / 13 Years ago, tue, may 10, 2011, 12:00:00

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?


More From » jquery

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


[#92318] Sunday, May 8, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cherish

Total Points: 734
Total Questions: 94
Total Answers: 86

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
;