jQuery: find input field closest to button

user2571510 picture user2571510 · Dec 3, 2013 · Viewed 78.4k times · Source

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.

Answer

MonkeyZeus picture MonkeyZeus · Dec 3, 2013

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'));
});