thevangelist thevangelist - 5 months ago 56
CSS Question

Fill a table cell with input type="checkbox"

I have table cells with checkboxes. What I want is the whole table cell to work as if you we're clicking the checkbox.

How to achieve this?

Answer

Is this what you are looking for?


CSS Method - JSFiddle

HTML

<table>
    <tr>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
    </tr>
    <tr>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
    </tr>
    <tr>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
        <td><label><input type="checkbox" /></label></td>
    </tr>
</table>

CSS

table{
    border-collapse:collapse;
}
td{
    padding:0px;
    border:solid 1px #000000;
}
label{
    display:block;
    padding:20px;
}

jQuery Method - JSFiddle

HTML

<table>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
    <tr>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
        <td><input type="checkbox" /></td>
    </tr>
</table>

CSS

table{
    border-collapse:collapse;
}
td{
    padding:20px;
    border:solid 1px #000000;
}

jQuery

$(document).on('click', 'td', function(){
    var target = $(this).find('input[type="checkbox"]');

    // If it's checked then uncheck it and vice versa
    target.prop('checked', !target.prop('checked'));
});