I have an HTML table (that gets its data from a database, but thats besides the point) that has a checkbox for each row. Is ther an easy way to allow the user to check the checkbox by clicking anywhere in the row, rather than the checkbox itself? I know this can be done using javascript, but is there an easy way to do it in rails? Anyone know of any gems or tutorials online?
2 Answers
Here's a working jsfiddle example: http://jsfiddle.net/3XZvV/2/
It uses the first checkbox in each table row. Put them in any <td>
. You can show the checkboxes, but you'll need to modify it to allow them to be clicked -- this design doesn't accommodate for clickable checkboxes since it fires the event when anything in that table row is clicked. (It was good enough for this question, but we're open to improvements.)
Here's the JavaScript to accomplish this:
$('.clickable tr').click(function() {
var c = $(this).find(':checkbox').filter(':first');
c.attr('checked', !c.attr('checked'));
$(this).toggleClass('selected');
});
Just put class="clickable"
on your table. In order to make it obvious that you can interact with rows, some CSS is nice. See the fiddle.

- 2,130
- 1
- 18
- 29
-
This looks perfect! Now i just need to implement it into my rails app. So all i need to do on the html is have a parent table with class="clickable" ? – Jonah Katz Aug 23 '11 at 15:45
-
Ugh, small glitch if you check the checkbox itself. Mundane detail. Will fix and post an updated jsfiddle. – Guttsy Aug 23 '11 at 15:45
-
Then yes, it should work. Any table with class `clickable` will have that applied. Rename if you want. For posterity, I'm going to try to fix this thing. (Part of my answer was derived from http://stackoverflow.com/questions/1467228/click-toggle-with-jquery.) – Guttsy Aug 23 '11 at 15:52
-
Do you know how to add to your jqery script to make the checkbox display hidden? – Jonah Katz Aug 23 '11 at 15:58
-
@Jonah see the updated fiddle CSS. `table.clickable tr input[type="checkbox"]:first-child` – Guttsy Aug 23 '11 at 16:04
-
1Actually, your method is better... degrades better :) – Guttsy Aug 23 '11 at 16:07
-
Found a slight problem.. If you add a row to the table that doesnt have a checkbox, the row is still clickable. – Jonah Katz Aug 23 '11 at 16:28
-
After the variable is defined, you can wrap the last two lines in `if(c.size()) { ... }` and that'll keep it from getting selected. CSS effects still apply for hovering. We can rebuild if that's an issue and make something a bit more flexible. – Guttsy Aug 23 '11 at 16:55
You'd have to use JavaScript. It's actually no that hard. Just add a click event for each TR that toggles the checked="checked" state of the checkbox, and changes the background color of the TR as well to show that it has been selected.
As a further enhancement, you could remove the checkbox altogether and use a hidden field instead, to save visual space. Just be sure your users are aware that the table rows are selectable.

- 3,615
- 1
- 26
- 32