Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Selecting nearest hidden input

Tags:

jquery

I have the following divs:

     <div class="vote">
     <input type="hidden" name="reply-id" value="83743">
     <a class="vote-up-0" title="Vote Up This Comment">up</a>
     <a class="vote-down-0" title="Vote Down This Comment">down</a>
     </div>


     <div class="vote">
     <input type="hidden" name="reply-id" class="reply-id" value="83745">
     <a class="vote-up-0" title="Vote Up This Comment">up</a>
     <a class="vote-down-0" title="Vote Down This Comment">down</a>
     </div>

(Yes, it's a blatent(ish) copy of SO code, I'm trying to see how they do it). So when a user clicks either vote up or vote down, it should find the hidden id.

This doesn't seem to work:

       $('a.vote-up-0').click(function() {

           var id = $(this).closest('.reply-id').val();
like image 524
jonnnnnnnnnie Avatar asked Apr 16 '11 17:04

jonnnnnnnnnie


2 Answers

closest works by going up the DOM tree to find the first element that matches a selector. It only matches ancestor elements. At no point does it look at sibling elements.

You want to use siblings:

$(this).siblings('.reply-id').val();
like image 148
lonesomeday Avatar answered Nov 15 '22 22:11

lonesomeday


If you want to generalise it slightly, to work with any input-element names, without necessarily knowing the names of the parent elements, you could use:

var idOfHiddenInput = $(this).parent().find('input:hidden:first').attr('id');

References:

  • parent()
  • find()
  • :hidden selector
like image 38
David Thomas Avatar answered Nov 15 '22 22:11

David Thomas