Fire function on key press if no inputs are selected

I am new to jQuery and am trying to run a function on keyPress if there are no selected inputs. I'm having trouble testing for focus. Below is what I currently have, but it is not working correctly. Any advice?

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

if (inputHasFocus == false){

    $("*").keypress(function (e) {
        // the function
    }); 
}

      

+2


source to share


3 answers


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

      



Something like that.

+2


source


I would try it like this:

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 used functions:

+1


source


You can also try something like this:

var inputHasFocus = false;

$('#myForm input').each(function () {

 if ($(this).is(":focus")) {
  inputHasFocus = true;
 }

};

      

0


source







All Articles