views:

122

answers:

1

Hello,

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.

+1  A: 

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?

Nick Craver
Thanks, that works fine!Only i made a changement into the code. Between the INPUT and the LABEL i put a IMG, and now your method does not function anymore. I think i misunderstand the prev() function of jquery... I thought prev() find the first previously type you defined, but it isn't?
Guido Lemmens 2
I think i understand now. Prev() looks only if it's about the previous element, that need to match.So for my example HTML i need the next code: $('.namelabel').live('click', function() { if ($(this).prev('img').prev("input").is(":checked")) { $(this).prev('img').prev("input").attr("checked", false); } else { $(this).prev('img').prev("input").attr("checked", true); } });
Guido Lemmens 2
@Guido Lemmens - Updated the answer for this :) `.prev()` finds the immediately previous element (if it matches, otherwise nothing), whereas `.prevAll()` finds all previous siblings, then filter for the first one you find. I simplified the code overall as well to do the same thing much faster.
Nick Craver