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
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 to share