user1221565
user1221565

Reputation:

Find the id of the closest input

How do I find the id of the closest input?

Here's the html

<input type="text" id="input1" size="36" name="input1" value="1" />
<input id="show_upload_image_link_button_1" class="button upload_images" type="button" value="Upload Image" />

Here's the jquery

$(document).ready(function() {
$("#show_upload_image_link_button_1").click(function() {
    alert(id of input1);
});
});

Upvotes: 0

Views: 206

Answers (3)

Dhiraj
Dhiraj

Reputation: 1871

Here, you probably trying to say the closest previous input. So, you can get the id of one like this: DEMO

$(document).ready(function() {
    $("#show_upload_image_link_button_1").click(function() {
        alert($(this).prev('input').attr('id'));
    });
});

If your targeted input is the second input, you could do .next instead like this:

$("#input1").click(function() {
        alert($(this).next('input').attr('id'));
});

Upvotes: 0

Bic
Bic

Reputation: 3134

For the closest parent, you can use:

$(this).closest('input').attr('id');

For the closest (older) sibling, you can use:

$(this).prev('input').attr('id');

For the closest (younger) sibling, you can use:

$(this).next('input').attr('id');

If you need to determine closest sibling (older/younger), you will have to write a custom function to determine the index of each in relation to the index of the context element:

var closestSibling = null;
var older = $(this).prev('input').attr('id');
var younger = $(this).next('input').attr('id');
var siblings = $(this).siblings('input').add(this);

var currentIndex = $(siblings).index(this);
var olderIndex = $(siblings).index(older);
var youngerIndex = $(siblings).index(younger);

if (Math.abs(youngerIndex-currentIndex) > Math.abs(olderIndex-currentIndex)) {
    closestSibling = older;
}
else {
    closestSibling = younger;
}

Upvotes: 2

putvande
putvande

Reputation: 15213

Try .siblings('input'):

$(document).ready(function () {
    $("#show_upload_image_link_button_1").click(function () {
        alert($(this).siblings('input').attr('id'));
    });
});

Fiddle

Upvotes: 0

Related Questions