Highlighting the clicked row of a striped HTML table

Solution 1:

http://jsfiddle.net/iambriansreed/xu2AH/9/

.table-striped class

.table-striped tbody tr.highlight td { background-color: red; }

... and cleaner jQuery:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});​

Update: .live() has since been deprecated. Use .on().

$('#mytable').on('click', 'tbody tr', function(event) {
    $(this).addClass('highlight').siblings().removeClass('highlight');
});​

Fixed: http://jsfiddle.net/iambriansreed/xu2AH/127/

Solution 2:

Increase the specificity of the .highlight

Learn more "CSS specificity" by reading this article and checking out the demo in this answer

//your normal green has "023"
//.table-striped  010
//tbody           001
//tr              001
//:nth-child(odd) 010 
//td              001 = 023
.table-striped tbody tr:nth-child(odd) td {
    background-color: green;
}

// your highlight only has "010"
//thus it can't take precedence over the applied style
.highlight{
    background-color: red
}

//a more specific highlight =  "033" will take precedence now
//.table-striped  010
//tbody           001       
//tr              001       everything is about the same except
//.highlight      010   <-- an added class can boost specificity
//:nth-child(odd) 010 
//td              001 = 033
.table-striped tbody tr.highlight:nth-child(odd) td {
    background-color: red;
}

Solution 3:

It is much easier, just use de Bootstrap css classes (like .info .warning .error or .success) to switch between the selected row and not selected. They have all the states for the row.

I used this, based on @iambriansreed answer:

$('#mytable tbody tr').live('click', function(event) {
    $(this).addClass('info').siblings().removeClass('info');
}

Solution 4:

Just edit the Bootstrap .table-striped CSS class to this:

.table-striped tbody tr:nth-child(odd),
.table-striped tbody tr:nth-child(odd) th {
    background-color: #f9f9f9;
}

.table-striped tbody tr:nth-child(even){
    background-color: yellow;
}

Remove all the td styling you do not want. Then it works.

When you click the row this style should also be applied:

.selected { background-color:#2f96b4 !important; }

It will not work without the !important.