views:

709

answers:

3

When a user clicks on the img at the end of the following "li", I want to get the value of the hidden input two elements previous.

<ul id="theLists">
    <li>
    <input class="checkbox" type="checkbox" name="row"/>
    <input class="contentId" type="hidden" value="64" name="id"/>
    <div id="64" class="editable">Peanuts for me</div>
    <img src="/img/delete.gif" alt="delete"/>
    </li>
</ul>

I tried this:

$(document).ready(function(){
    $("#theLists img").click(function(){
        var contentId = $(this).closest("input[name='id']").val();   
    });

To no avail. Any Ideas? I need to set a var with the row id, which in this case is "64".

+5  A: 

closest(...) gets the closest parent node, not the closest sibling.

There are, in fact, multiple ways to do what you want.

Try these:

var contentId = $(this).siblings("input[name='id']").val();

var contentId = $(this).parent().children("input[name='id']").val();

var contentId = $(this).prev().prev().val();
Jeff Meatball Yang
Thanks, using sibling method. Also good to know that compound prev()s can be used.
kevtrout
No offence to Jeff, but while this answers your direct question it doesn't cover you if you ever need to move the IMG tag, for example within a span or div in order to style it.
tags2k
Of course it only answers the direct question. If there was mention of any general "how to set this input" or the like, my answer would have been different. However, if the question specifies a methodology, I have to assume that's what is needed, versus any advice on how to handle what-if's. Hope I don't sound offensive, just want to clarify is all.
Jeff Meatball Yang
A: 

Nice and cheap:

var contentId = $(this).parents('li:first').find('.contentId').val();
tags2k
+1  A: 

See complete solution here.

You can move the id attribute to the containing <li>, remove the hidden field and just use:

var contentId = $(this).parent().get(0).id;

The advantage here is that in the future you can add other actions, like "edit", etc. without a need to worry about a sibling's position.

Claude