views:

100

answers:

3

Hello,

I am using a e.which of jquery for running a function on press of ENTER, but I want this function to be called only if the particular input field is focused (where the cursor is blinking).

My current jquery function.

$(document).keyup(function(e) {
    if (e.which == 13) {
        var page = $("#userpage").val();

        if(page > 0) {
            $("#search").click();
        } else {
            $('.save').click();
        }
    }
});

I want that $("#search").click(); to be called only if the #search_text is focused or has some input, because I have few more input fields and users tend to press enter, and on Enter this function is called.

Thank You.

A: 

Bind the event for the #search_text element, instead of the whole document. That way it'll only be triggered when the element has the focus.

reko_t
+2  A: 

I would attach the event listener to that specific input element:

$('#search_text').keyup(function(e) {
    if (e.which == 13) {
        // do it
    }
});
clownbaby
I agree but would suggest using the `keypress` event rather than the `keyup` event, since it will fire sooner and also has reliable character codes for printable characters in all mainstream browsers.
Tim Down
+1  A: 

just add this line to your function inside your second if statement:

$('#search_text').focus(function()
TStamper