0

How do you determine if any input within div1 is focused with jQuery?

<div id="div1">
    <input type="text" id="input1">
    <div id="div2">
        <input type="text" id="input2">
    </div>
</div>
2
  • @Teemu I believe the OP is referring to focused text inputs. Commented Jun 12, 2014 at 18:14
  • @Teemu: Yes, focused* Commented Jun 12, 2014 at 18:16

2 Answers 2

2
if($("#div1 input:focus").length > 0){
   alert('An input is selected');
}else{
   alert('No inputs selected.');
}

Fiddle: http://jsfiddle.net/6r8RQ/

Docs: :focus, .length.

Sign up to request clarification or add additional context in comments.

Comments

0

Short and to the point:

if ( $("#div1").find("input:focus")[0] ) {...}

Given a jQuery object that represents a set of DOM elements, the .find() method allows us to search through the descendants of these elements in the DOM tree and construct a new jQuery object from the matching elements. The .find() and .children() methods are similar, except that the latter only travels a single level down the DOM tree.

Source: http://api.jquery.com/find/

JSFiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.