Manuel Hoffmann Manuel Hoffmann - 1 year ago 63
HTML Question

Toggle checkbox when clicking table row without javascript

I have a HTML table in my HTML5/PHP web application (mobile). Users should be able to select a row by clicking anywhere on the row. A selected row should also change color.

The table is structured like this:

<td><input type="checkbox" name="ids[]" value = "1"></td>
<td>This is the name</td>

(name = ids[] is used for PHP to get a list of selected values)

Since Phones don't have very much performance in JavaScript, I want to avoid using it if possible. Is it somehow possible to accomplish this with CSS/HTML?

If not, what is the most performant way using JavaScript?

Answer Source

It is not possible to handle click events without Javascript. It is possible to use some ugly hacks, which will make your markup and styles horrible and impossible to read, to make it look like you can handle click events in CSS, but this is not really practical in a production app, especially on mobile, and it's just generally not a very good idea.

So we're down to Javascript. The first consideration if you want performant Javascript in browser is to steer away from libraries like jQuery, which add a lot of boiler-plate wrapper code around everything you ever do.

So you want to implement it in Javascript, in the simplest and most performant way, that would be something along the lines of this:

// yep, window.onload. You want compat in mobiles, you have to stupidify your
// code a *lot*
window.onload = function() {
    var i, l,
        trs = document.getElementsByTagName('TR');

    for (i = 0, l = trs.length; i < l; i++) {

function clickHandler()
    if (this.isSelected) { // expando properties. sorry, compat again
        // change color, check checkbox, whatever
        this.isSelected = false;
    } else {
        // opposite of above
        this.isSelected = true;

function attachClickHandler(tr)
    tr.onclick = function() {;

Horrible, isn't it?

OR could just use jQuery mobile, and worry about performance if it actually becomes a real issue that users complain about, instead of a theoretical problem.

Note: in general I am not a fan of jQuery but in the mobile world, where all bets are off in terms of available features, you really have to be a sadist not to use it (or something like it).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download