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?
$("#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.
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
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With