Understanding the actions taken on a website is very important for usability purposes, but also personal sanity. It’s common knowledge that if your website drives a visitor insane they’re not going to come back as often,
…at least not AS often anyway.
So here is a great way to give some feedback to a user who selects a row in an HTML table. We’ll do this by using jQuery’s lovely toggleClass.
If you wanted a table on your site to indicate a row has been selected by changing the background color of a selected row, then you would add an ID to the table. The jQuery selector for such a table would look like this,
$(‘#table_ID tbody tr’)
By the way, it’s best to wrap your table rows within a ‘tbody’ tag to separate them from the table’s header information.
The rest of the jQuery looks like this,
$(‘#table_ID tbody tr’).click(function () {
$(this).toggleClass(‘class_name’);
});
(this) is a referent to the selected HTML element, in this case, any ‘tr’ inside of a ‘tbody’ attached to the table with the given ID.
Let’s say we defined a CSS class that would change the background color of a selected row and called it .pickme then set our table’s ID to “newtable”, the code would look like this.
$(‘#newtable tbody tr’).click(function () {
$(this).toggleClass(‘pickme’);
});
Using the toggleClass function we have found a fun and easy way to indicate to the user a row has been selected. Since the toggle will turn off the .pickme class when it is clicked again, the user gets instant feedback when selecting or deselecting table rows with just a click.
Of course, by giving your tables a class you could make every table on your site behave this way.
Here is a simple example of an HTML table that changes the background color of a row when that row is clicked.
<Simpletable>
Notice that because we didn’t target the ‘thead‘ tag with our jQuery selector the row inside the ‘thead‘ doesn’t change when it’s clicked.
