Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

e.which ENTER key enabled only if input field focus

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.

like image 271
Shishant Avatar asked Oct 28 '09 13:10

Shishant


2 Answers

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

$('#search_text').keyup(function(e) {
    if (e.which == 13) {
        // do it
    }
});
like image 53
danjarvis Avatar answered Nov 15 '22 07:11

danjarvis


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

$('#search_text').focus(function()
like image 23
TStamper Avatar answered Nov 15 '22 07:11

TStamper