Heather Roberts
Heather Roberts

Reputation: 55

Selecting Children without ID or Class names

I am trying to select a input textbox from within 2 parent divs with classes and/or ids. There are so many examples and methods of doing this that I have tried so many that I have resorted to posting this question for assistance in the event that someone else may encounter this issue.

CODE

<div class="tblsearch">
    <div id="ElementCount10_filter" class="dataTables_filter">
        <label>
            Search:
            <input type="text">
        </label>
    </div>
    <div id="ElementCount10_info" class="dataTables_info"></div>
    <div class="clear"></div>
 </div>

I have tried the following:

$(this).parent(".dataTables_filter").children("label").children("input").click(function () { alert('we got here'); });

$(".tblsearch.dataTables_filter label > input").click(function () {
    alert('hovered');
});

$(this).parent(".dataTables_filter").children("input").click(function () { alert('we got here'); });

I have been unable to access the selector. I need to check if someone clicks into the box and fire off a function. This seems super easy and I must be missing something in my syntax.

Thanks in advance for your help!

Upvotes: 0

Views: 121

Answers (4)

kalley
kalley

Reputation: 18462

fiddle

$('.dataTables_filter').on('click', 'input', function() {
    alert('here we are!');
});

Try this. If you need it more specific, you can do input[type="text"] or something.

This uses event delegation (see @Methletics's link for more information). So, this would handle any clicks on any inputs within the parent.

Upvotes: 4

Penguinator
Penguinator

Reputation: 641

children only searches one level down. To search multiple levels down, use find instead.

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

Working jsfiddle:

http://jsfiddle.net/Vs5zZ/2/

Upvotes: 0

Adrift
Adrift

Reputation: 59779

The problem with the second selector is that you didn't have a space between the class names, including a space will make it work like expected - as the <div> with class .tblsearch is an ancestor of the <div> with class .dataTables_filter

$(".tblsearch .dataTables_filter label > input")

http://jsfiddle.net/MxffP/

Upvotes: 1

Deepak Biswal
Deepak Biswal

Reputation: 4320

Here is the [DEMO].

$(".dataTables_filter").children("label").children("input").click(function () { alert('we got here'); });

$(".dataTables_filter label > input").click(function () {
    alert('hovered');
});

$(".dataTables_filter").find("input").click(function () { alert('we got here'); });

Upvotes: 0

Related Questions