How do I find closest element with jQuery

Viewed 40107

I have the following HTML code:

<td>
  <input type="text" size="40" value="" name="related_image" id="related_image">  
  <input type="button" class="button addImage" value="Get image url">
</td>
<td>
  <input type="text" size="40" value="" name="alternative_image" id="alternative_image">  
  <input type="button" class="button addImage" value="Get image url">
</td>

I need to figure out which button I click, then add some text to the nearest input text field.
E.g. if I click the button in the first <td>, then I need to input some text into related_image text field.

I've tried with the followin jQuery, but it's not working:

jQuery('.addImage').click(function() {
  var tmp = jQuery(this).closest("input[type=text]").attr('name');
  alert(tmp);
});

(I'm just retrieving the inputs name for testing.)

I think I might have to use find and / or siblings. But I'm not quite sure how.

Any help appreciated.

EDIT

I just managed to use this code
addImageEvent = jQuery(this).prevAll("input[type=text]:first")

Is using prevAll a bad choice?

3 Answers

Here is a 'closest' implementation that aims at descendants instead of parents:

$.fn.nearest = function(selector) {
    var nearest, node = this, distance = 10000;
    node.find(selector).each(function(){
        var n = $(this),
            d = n.parentsUntil(node).size();
        if (d < distance) {
            distance = d;
            nearest = n;
        } else if (d == distance) {
            nearest.add(this);
        }
    });
    return nearest;
};
Related