Skip to content
Advertisement

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.

Advertisement

Answer

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

$('#search_text').keyup(function(e) {
    if (e.which == 13) {
        // do it
    }
});
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement