Guido Lemmens 2
Guido Lemmens 2

Reputation: 2307

jquery Tree Traversal prev() problem

I like to click a label and check the previous checkbox. I've tried the next code, but this is not working. I have tried for 2 hours, but what am i missing?

JQUERY

jQuery(document).ready(function() {
    $('.namelabel').live('click', function() {
        if ($(this).prev("input:checked").val() != null) {
            $(this).prev("input").removeAttr("checked");
        } else  {
            $(this).prev("input").attr("checked","checked"); 
        }
    });
});

HTML
<input type="checkbox" class="check" name="example" /> <img src="image.png" class="modelinfo" /> <label class="namelabel">John Doe</label>

Who can help me to solve this question? Many thanks!

p.s. I know i can easy solve this with the <label for=""> tag, but that is not the question.

Upvotes: 0

Views: 570

Answers (1)

Nick Craver
Nick Craver

Reputation: 630389

You can do it like this:

$('.profilename').live('click', function() {
  var cb = $(this).prevAll(":checkbox:first");
  cb.attr("checked", !cb.is(":checked")); 
});

Also, just noticed your class doesn't match, in your html it's namelabel but in your jQuery it's profilename, is it a different example or should they match up?

Upvotes: 1

Related Questions