I've got a division (<div>) which contains a form and I want to find out using jQuery if any of the <input>s have focus and if none of them have I want to call a function.
What is the best way of doing this?
Rough idea of div/form structure.
<div id="section1">
<form ...>
<input type="text" id="v1">
<input type="text" id="v2">
<input type="text" id="v3">
<input type="text" id="v4">
<input type="checkbox">
</form>
</div>
Thanks.
Select the input elements and filter out the focussed ones:
$("#section1 input").filter(":focus")
should be empty, then none of the elements has focus. Actually, you have several different ways of selecting to achieve the same result.
if ($("#section1 input:focus").length === 0){
callYourFunction();
}
since 0 is a falsy value the above if-condition is practically the same like:
if ( !$("#section1 input:focus").length )
Beware though that checking for falsy values in this way is not always recommended. Often it's better, more obvious and less error prone if you write it the "normal" (first) way.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With