开发者

e.which ENTER key enabled only if input field focus

开发者 https://www.devze.com 2022-12-09 20:52 出处:网络
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).

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 ha开发者_Python百科ve few more input fields and users tend to press enter, and on Enter this function is called.

Thank You.


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

精彩评论

暂无评论...
验证码 换一张
取 消