Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery: find input field closest to button

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.

like image 487
user2571510 Avatar asked Dec 03 '13 16:12

user2571510


People also ask

What is closest in jquery?

The closest() method returns the first ancestor of the selected element. An ancestor is a parent, grandparent, great-grandparent, and so on. The DOM tree: This method traverse upwards from the current element, all the way up to the document's root element (<html>), to find the first ancestor of DOM elements.


3 Answers

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'));
});
like image 76
MonkeyZeus Avatar answered Oct 21 '22 19:10

MonkeyZeus


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()

like image 39
Adil Avatar answered Oct 21 '22 18:10

Adil


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.

like image 6
sPaz Avatar answered Oct 21 '22 17:10

sPaz