Ruttyj
Ruttyj

Reputation: 933

Auto detect and check all for that table column

I am attempting to make a check that once clicked will check all the boxes in that specific column of the table. So say if it was in column 3: when clicked it would check all the checkboxes that are in all the rows of column 3. But I also want it to detect which column it is in.

Here is what I have so far, I have got it to do one or the other but not both at the same time:

            $('.checkall').click(
                function(){
                    var col = $(this).parent().children().index($(this));
                    $(this).parent().parent().parent().parent().find("td:eq("+col+") input[type='checkbox']").attr('checked', $(this).is(':checked'));   
                }
            );

Upvotes: 1

Views: 1940

Answers (2)

dgilland
dgilland

Reputation: 2748

This should work:

$(".checkall").click(function(){
    var $table = $(this).closest("table");
    var col = $(this).closest("tr").children().index($(this).closest("td"));
    var index = col + 1; // offset for nth-child
    $table.find("td:nth-child("+index+") input:checkbox").attr("checked",$(this).is(":checked"));
});

jsfiddle.net

Upvotes: 1

Benjamin Crouzier
Benjamin Crouzier

Reputation: 41895

This will do the work. Comment if this is not exactly what you want

HTML:

<table border="1">
    <tr>
        <td>All<input type="checkbox" value="" class="checkAll"></td>
        <td><input type="checkbox" value=""></td>
        <td><input type="checkbox" value=""></td>
        <td><input type="checkbox" value=""></td>
    </tr>
    <tr>
        <td>All<input type="checkbox" value="" class="checkAll"></td>
        <td><input type="checkbox" value=""></td>
        <td><input type="checkbox" value=""></td>
        <td><input type="checkbox" value=""></td>
    </tr>
</table>

javascript:

<script type="text/javascript">
    $('tr').find('input:checkbox').not('.checkAll').change(function()
    {
        var checkboxes = $(this).parent().parent().find(':checkbox').not('.checkAll');
        var checkAll = $(this).parent().parent().find('.checkAll');
        if (!checkboxes.not(":checked").not(".checkAll").length)
            checkAll.attr("checked", true);
        if (!checkboxes.filter(":checked").not(".checkAll").length)
            checkAll.attr("checked", false);

    });
    $(".checkAll").change(function()
    {
        $(this).parent().parent().find(':checkbox').attr('checked', this.checked);
    });
</script>

Upvotes: 0

Related Questions