How to select adjacent hidden input value using jQuery?

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

<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 install var with the string identifier, which in this case is "64".

+5
source share
3 answers

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

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

Try the following:

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

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

var contentId = $(this).prev().prev().val();
+10
source

See the complete solution here.

id <li>, :

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

, , "" .., .

+2

Nice and cheap:

var contentId = $(this).parents('li:first').find('.contentId').val();
0
source

All Articles