jQuery: find input field closest to button
Asked Answered
D

3

21

I have a large HTML form with multiple input fields (one in each row). Among these I have several fields with a specific class that appear left from a button. There are no other buttons or fields in these rows so they only contain the field and button as below.

How can I get the ID of such a field when clicking on the button right from it, i.e. closest to it ?

All fields in question look like this:

<input type="text" class="dateField" data-date-format="yyyy-mm-dd" id="field1" name="field1" />

All buttons in question look like this:

<button type="button">Select Date</button>

Thanks for any help with this, Tim.

Draggletailed answered 3/12, 2013 at 16:52 Comment(5)
It would be more helpful if you showed the html of the entire row so that we can see the exact relationship between the button and the datefield. Would also like to see any code that you have produced to try to solve this issue.Incommensurable
Well assuming that the input and the field are on the same depth you can use .siblings() or a combination or .parent() and .children(). If you need the id to dynamically set the for attribute to cause a click on the label to focus the input, there is another way : just put the input inside of the label.Bumble
$('tr button').on('click',function(){var id = $(this).closest('tr').find('.dateField')[0].id})Wichern
use like input[type=button]+input.dateFieldSharpwitted
Thanks, all ! - @ A.Wolff: this is great and already enough for what I needed in this specific case.Draggletailed
N
43

Because <input> is to the left of <button> you can find it like this:

$('button').on('click', function(){
    alert($(this).prev('input').attr('id'));
});

If <input> was after <button> then you can find it like this:

$('button').on('click', function(){
    alert($(this).next('input').attr('id'));
});
Nall answered 3/12, 2013 at 16:59 Comment(1)
@skwidbreth Glad you found this useful!Nall
B
17

You can go to parent of button using parent() and the find the input in descendants using find()

OR, if you have multi-level descendant

$(this).parent().find('.dateField')

OR, if you have single level descendants

$(this).parent().children('.dateField')

or

$(this).siblings('.dateField');

Similarly you can use next() or prev()

Boony answered 3/12, 2013 at 16:55 Comment(1)
.find() is recursive. .children() could/should be faster.Bumble
H
6

Use .prev() or .next() if they're next to each other. (This should be fastest.) Otherwise you can also use .closest() to simply find closest instance of that class.

The documentation should be more than enough help.

Edit: You can also use .siblings() to search through siblings of that element.

Hernandez answered 3/12, 2013 at 16:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.