jQuery: find input field closest to button

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

Leave a Comment