tags:

views:

64

answers:

2

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?

+2  A: 

.closest() finds a parent, in this case you need .siblings(), like this:

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

Or if the format is always consistent like your example, just use .prev(), like this:

jQuery('.addImage').click(function() {
  var tmp = jQuery(this).prev().attr('name');
  alert(tmp);
});
Nick Craver
Yup. As I commented above - I mixed parent / child, thinking siblings = children. Thansk for the solution :)
Steven
+2  A: 

Try:

var tmp = $(this).siblings(":text").attr("name");

The closest() method you're using finds the closest ancestor, which is not what you want here.

cletus
aaaah - somehow I though that siblings = children. But siblings = brother / sister. Thanks. I see there are multiple solutions to this "problem".
Steven