Ben Kilah
Ben Kilah

Reputation: 3475

Jquery closest not working

I've trying for a while to now to figure out why I can never get the "closest" function from jquery to work.

Say I have this code;

<form>
<input type='text' name='q'>
<a href='javascript:void(0);' id='search_items'>Search</a>
</form>

Why does the following always alert "undefined"?

$("#search_items").bind('click', function () {
    var q = $(this).closest("input[name=q]").val();
    alert(q);
});

Thanks in advance! Cheers, Ben

Upvotes: 1

Views: 3512

Answers (1)

alex
alex

Reputation: 490173

Your input element is a sibling, not an ancestor of #search_items. You want siblings() (or prev(), dependent on the flexibility required).

$("#search_items").bind('click', function () {
    var q = $(this).siblings("input[name='q']").val();
    alert(q);
});

Upvotes: 6

Related Questions