Chris Frank
Chris Frank

Reputation: 4442

Jquery detect input focus

I am creating a conversion web app to teach myself Javascript. The user can input data with a number pad (basically a calculator without the operators). I also set up a function to detect keystrokes (1-9) which insert data just like the number pad. And also character 'c' which clears all data

My problem is that I also have a search field (which uses auto complete to enable the user to search for other conversions). I dont' want the user to search for something using the 'c' or number keys, and have it enter data into both the number pad, and search field.

My idea was to create a if statement to determine if the search field was active (focused), and if it was to change a variable (enabled) to false, thus disabling the keystroke detection.

The problem I am having is that the function holding the if statement with the focus attribute is not working.

If my rambling made no sense hopefully the code will clear things up.

Here is the if statement with the focus attribute

$(document).ready(function(){
    if($(':focus').attr('#searchInput') == 'input')){
        enabled === false;
    }
});

Here is the code for key stroke detections (I omitted the redundant parts to save space

document.onkeydown = function(event){
    var key = event.charCode || event.keyCode;
    if(enabled === true){
        if(key === 67){
            clearInput(input); //Clears form input (input is my form ID)
        }else if(key === 48){
            writeInput(input, zero); //Zero is a var equaling 0
        }
        ...
    }else{
        return false; //if enabled is false don't detect keystrokes
    }
};

Any help would be greatly appreciated. If anything doesn't make sense I will be happy to explain (or edit the post.)

Upvotes: 1

Views: 5917

Answers (1)

Peter
Peter

Reputation: 16923

$(document).keyup(function(e){
   if($('#searchInput').is(':focus')) {
      return ; // search field is focused, ignore other part of function
   }
   var key = e.which;
   // do your code here
});

Upvotes: 4

Related Questions