最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - e.which ENTER key enabled only if input field focus - Stack Overflow

programmeradmin3浏览0评论

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.

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.

Share Improve this question asked Oct 28, 2009 at 13:14 ShishantShishant 9,29415 gold badges59 silver badges81 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 10

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

$('#search_text').keyup(function(e) {
    if (e.which == 13) {
        // do it
    }
});

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

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

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.

when we apply the bind to $(document), the bind occurs when the document has focus. We can use the same thing here. By using $(#search-text) in the keybind, we make it so that the keybind is only triggered when #search-text is focused.

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

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

You also need to add: e.preventDefault();

$('document').keyup(function(e) {
  if (e.keyCode == '13') {
     e.preventDefault();
     var page = $("#userpage").val();
   }
});
发布评论

评论列表(0)

  1. 暂无评论