Search code examples
jqueryparentcheckbox

jQuery: Targetting an element's parent's checked checkboxes


I want to bind a function to all links with a class called 'click' that will alert the values of all of the checkboxes that are 'checked' in that link's parent div. I must not understand how the jQuery parent function works, because I'd expect the two JS codes below to do the same thing, only the second more flexible.. But the first one (specific targeting) works whereas the second JS example doesn't.

Any pointers on what I'm doing wrong would be awesome!

HTML:

<div id="wrapper">
<ul>
    <li><input type="checkbox" name="blue" value="blue" /></li>
    <li><input type="checkbox" name="red" value="red" /></li>
    <li><input type="checkbox" name="green" value="green" /></li>
</ul>

<a href="#" class="click">Submit</a>
</div>

Working JS:

$('.click').click(function() {

    var colors = [];

    $('#wrapper :checkbox:checked').each(function(i){                         

        alert($(this).val());

        colors[i] = $(this).val();  

    });

    return false;

});

Not Working JS:

$('.click').click(function() {

    var colors = [];

    $(this).parent(':checkbox:checked').each(function(i){                         

        alert($(this).val());

        colors[i] = $(this).val();  

    });

    return false;

});

Solution

  • Change your second block of code to this and it should work:

    $('.click').click(function() {
    
        var colors = [];
    
        $(this).parent().find(':checkbox:checked').each(function(i){                         
    
            alert($(this).val());
    
            colors[i] = $(this).val();  
    
        });
    
        return false;
    
    });
    

    The parent function searches though your ancestors and looks for elements that match the string provided. If no string is provided, then it returns your immediate ancestor. The combination of parent() and find('...') should do what you want to do.

    If you wanted to guarantee that you are grabbing the containing div, you could also use .parent('div').find(':checkbox:checked').