views:

770

answers:

2

I am new to jquery and am trying to fire a function on a keyPress if there are NO inputs selected. but I am having trouble with testing for focus. Below is what I currently have but it isn't working correctly. Any advice?

var inputHasFocus = false;
$('#myForm :input').each(is(":focus")){

    inputHasFocus = true;
};

if (inputHasFocus == false){

    $("*").keypress(function (e) {

     // the function
    }); 
}
+1  A: 
var focusedInputs = $("#myForm input:focus");
if (focusedInputs != null && focusedInputs.length > 0) { inputHasFocus = true; }

Something like that.

Plan B
Thanks Plan B worked great once I put it inside the keypress. It looks like the other response would work as well but I tried this first and it worked so I didn't try the other. Thanks to both of you!$("*").keypress(function (e) { var inputHasFocus = false; var focusedInputs = $("#myForm input:focus"); if (focusedInputs != null } if(inputHasFocus != true) { // the function to run each time a key is pressed with no input selected } }});
Lance
I'm glad it worked for you! :)
Plan B
+1  A: 

I would try it as follows:

var inputHasFocus = false;

$('#myForm :input').focus(function() {
    inputHasFocus = true; // Set true if a Form-Field is selected
}).blur(function() {
    inputHasFocus = false; // Set false if a Form-Field has left
});

$("*").keypress(function() {
    if(!inputHasFocus) {
        // check if(inputHasFocus) after the keypress has done
        // otherwise you have the basic value in the var inputHasFocus 
        // here you can run your function...
    }
});

jQuery Documentation-Links to the used functions:

snuffer.ch