Checkbox jQuery

Cambiar el estado de todos los checkbox de una columna a partir del check de la cabecera. Con jQuery

by Alejandro Hernández

HTML

<table>
    <thead>
        <tr>
            <th><input type="checkbox" />head1</th>
            <th><input type="checkbox" />head2</th>
            <th><input type="checkbox" />head3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td><input type="checkbox" />td11</td>
            <td>td21</td>
            <td>td31</td>
        </tr>
        <tr>
            <td><input type="checkbox" />td12</td>
            <td><input type="checkbox" />td22</td>
            <td>td32</td>
        </tr>
        <tr>
            <td><input type="checkbox" />td13</td>
            <td><input type="checkbox" />td23</td>
            <td>td33</td>
        </tr>
        <tr>
            <td><input type="checkbox" />td14</td>
            <td>td24</td>
            <td><input type="checkbox" />td34</td>
        </tr>
    </tbody>
</table>

CSS

table {
    border-collapse:collapse;
}
table, th, td {
    border: 1px solid black;
}

JavaScript

$("table th input[type=checkbox]").click(function() {
    $(this).closest("table")
        .find("td:nth-child(" + ($(this).closest("th").prevAll().size() + 1) + ") input[type=checkbox]")
        .prop('checked', $(this)[0].checked);
});

/* //Código legible
$("table th input[type=checkbox]").click(function () {
    var headerCheckbox = $(this);
    var columnIndex = headerCheckbox.closest("th").prevAll().size() + 1;
    headerCheckbox.closest("table")
      .find("td:nth-child(" + columnIndex + ") input[type=checkbox]")
      .prop('checked', headerCheckbox[0].checked);
});*/