I have the following structure in a form:
<div class='full'>
<div class='half'>
<label>Book</label>
<select class='collection_ID'>
<option></option>
<option value="1">Geen leuk boek / € <span>14.50</span></option>
<option value="2">Cool boek! / € <span>24.50</span></option>
</select>
</div>
<div class='half'>
<label>Find a book</label>
<input type='text' class='invoke_search'>
</div>
</div>
<button class='clone'>Another Book</button>
And here is my question. I have an input field
<input type='text' class='invoke_search'>
If a user decides to type some text and then moves on (i.e blur event) he/she wants to search a book by title in the pretty close to it.
My jQuery function is the following:
$('.invoke_search').live('blur', function()
{
var needle = this.value;
var haystack = $(this).parent().parent().find('select').children();
search(needle, haystack);
});
It’s on a .live() event listener (or however you call that), because the clone button will create a copy/clone of the .. so a user can add more books to the form, this also means that I cannot use a unique ID on the , since the user has to search in a single for an option and not in every select.
Now to get to my question, the following part is kind of hardcoded:
var haystack = $(this).parent().parent().find('select').children();
So I am looking for a way to use something like:
$(this).closest('select');
As if my form structure looked like:
<div class='full'>
<label>Book</label>
<select class='collection_ID'>
<option></option>
<option value="1">Geen leuk boek / € <span>14.50</span></option>
<option value="2">Cool boek! / € <span>24.50</span></option>
</select>
<label>Find a book</label>
<input type='text' class='invoke_search'>
</div>
This would make styling pretty hard, so is there a way to use .closest() or .find() in some smart way instead of ‘hardcoded’ parent().parent().find()?
Thanks in advance
If there’s always a
<div class="full">wrapper then perhaps this would work:You just need something that contains both your
<input>and<select>that can easily be identified using a selector, then hand that selector toclosestto find the starting point forfind.