Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery check elements to make sure none are in focus

Tags:

html

jquery

loops

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.

like image 214
Simon R Avatar asked Nov 30 '25 09:11

Simon R


1 Answers

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.

like image 115
Christoph Avatar answered Dec 01 '25 23:12

Christoph