jonnnnnnnnnie
jonnnnnnnnnie

Reputation: 1239

Selecting nearest hidden input

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();

Upvotes: 9

Views: 24960

Answers (5)

Anoj Saranga
Anoj Saranga

Reputation: 1

Since you are wrapping the hidden element inside a div you can use the below method too.

$(this).closest('div').find('input[name="reply-id"]').val() 

This will proceed to the closest DOM element and will find the hidden input element with the name "reply-id".

Upvotes: 0

Ron Harlev
Ron Harlev

Reputation: 16673

Why not attach the ID as a custom attribute to the clickable object itself. Then you can just access it with .attr. You could for example put a val tag like this:

<a class="vote-up-0" title="Vote Up This Comment" val="2345">up</a>

then access it with

$(this).attr("val")

This might eliminate the need for the hidden field

Upvotes: 3

HasanG
HasanG

Reputation: 13161

Try this code

$(document).ready(function () {
    $('a.vote-up-0').click(function () {
        var id = $(this).parent().find('.reply-id').val();
    });
});

Upvotes: 2

David Thomas
David Thomas

Reputation: 253318

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:

Upvotes: 9

lonesomeday
lonesomeday

Reputation: 237855

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();

Upvotes: 15

Related Questions