DEV Community

Cover image for [NO JS] Checkable table row with highlighting
Rémy F.
Rémy F.

Posted on

[NO JS] Checkable table row with highlighting

Tips: This approach works for both checkbox and radio table !

Let's start with the classic :

One selectable line table (radio based):

<table>
    <thead>
        <th></th>
        <th>mono-selection</th>
    </thead>
    <tbody>
        <tr>
            <td><input type=radio name=radio value=radio1 required></td>
            <td>radio1</td>
        </tr>
        <tr>
            <td><input type=radio name=radio value=radio2 required></td>
            <td>radio2</td>
        </tr>
        <tr>
            <td><input type=radio name=radio value=radio3 required></td>
            <td>radio3</td>
        </tr>
    </tbody>
</table>
Enter fullscreen mode Exit fullscreen mode

Using the following CSS rules we can highlight the selected row when it input is checked:

tr {
    /* https://github.com/w3c/csswg-drafts/issues/1899 */
    transform: scale(1);
    position: relative;
}

/* The highlight magic is here (webkit only) */
:checked::before {
    content: ' ';
    position: absolute;
    display: block;
    top: 0;
    left: 0;
    bottom: 0;
    right: 0;
    background: yellow;
    opacity: .5;
    z-index: -1;
}

/* Moz hack to enable :before on radio
[type=radio]{appearance: none;}
[type=radio]:not(:checked)::before{content: '⚪';}
[type=radio]:checked::before{content: '🔘';padding: 3px 5px;}
*/
Enter fullscreen mode Exit fullscreen mode

Trick: If the <table> belongs to a <form>, you can automatically hide/show it actions buttons when a line is selected (but be sure to mark it radio required !).

<style>
:invalid .if-valid{
    display: none;
}
</style>
<form>
    <table>...</table>
    <footer class=if-valid>
        <button>You got me !</button>
    </footer>
</form>
Enter fullscreen mode Exit fullscreen mode

The highlighting CSS rules also work with checkboxes. But since checkbox are optionals you can forget about the funny hide-show trick.

Multi selection table (checkbox based):

<table>
    <thead>
        <th><input type=checkbox
                onclick="[...closest('table').querySelectorAll('tbody [type=checkbox]')].forEach(box=>box.checked=checked)">
        </th>
        <th>title</th>
    </thead>
    <tbody>
        <tr>
            <td><input type=checkbox name=chk value=chk1></td>
            <td>chk1</td>
        </tr>
        <tr>
            <td><input type=checkbox name=chk value=chk2></td>
            <td>chk2</td>
        </tr>
        <tr>
            <td><input type=checkbox name=chk value=chk3></td>
            <td>chk3</td>
        </tr>
    </tbody>
</table>

Enter fullscreen mode Exit fullscreen mode

Full Demo:

Tips: it includes a form submit alert, so you can see selected values that would have been submitted to the form action endpoint

Top comments (0)