E.which the ENTER key is only enabled if the focus of the input field

I use e.which jquery to run the function when ENTER is pressed, but I want this function to be called only if the special 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 $ ("# search"). click (); to call, only if #search_text is focused or has some input, because I have several input fields and users usually press the enter button and press Enter. This function is called.

Thanks.

+6
javascript jquery
source share
4 answers

I would attach an event listener to this particular input element:

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

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

 $('#search_text').focus(function() 
+1
source share

Bind an event to the #search_text element instead of the entire document. Thus, this will only work when the element has focus.

0
source share

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

 $('document').keyup(function(e) { if (e.keyCode == '13') { e.preventDefault(); var page = $("#userpage").val(); } }); 
-one
source share

All Articles