I need your help,
How can I, using jQuery,
Change the background color of the selected row in my table (for this example, let's use the the css class "highlighted"
and if the same row is clicked on again, change it back to its default color (white) select the css class "nonhighlighted"
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.highlighted {
background: red;
}
.nonhighlighted {
background: white;
}
</style>
</head>
<body>
<table id="data" border="1" cellspacing="1" width="500" id="table1">
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
HTML | <tr> bgcolor Attribute The HTML <tr> bgcolor Attribute is used to specify the background color of a table row. It is not supported by HTML 5. Attribute Values: color_name: It sets the background color by using the color name.
.highlight { background-color: red; }
If you want multiple selections
$("#data tr").click(function() {
$(this).toggleClass("highlight");
});
If you want only 1 row in the table to be selected at a time
$("#data tr").click(function() {
var selected = $(this).hasClass("highlight");
$("#data tr").removeClass("highlight");
if(!selected)
$(this).addClass("highlight");
});
Also note your TABLE tag has 2 ID attributes, you can't do that.
Create a css class that applies the row color, and use jQuery to toggle the class on/off:
CSS:
.selected {
background-color: blue;
}
jQuery:
$('#data tr').on('click', function() {
$(this).toggleClass('selected');
});
The first click will add the class (making the background color blue), and the next click will remove the class, reverting it to whatever it was before. Repeat!
In terms of the two CSS classes you already have, I would change the .nonhighlighted
class to apply to all rows of the table by default, then toggle the .highlighted
on and off:
<style type="text/css">
.highlighted {
background: red;
}
#data tr {
background: white;
}
</style>
$('#data tr').on('click', function() {
$(this).toggleClass('highlighted');
});
Here's a possible solution that will color the entire row for your table.
CSS
tr.highlighted td {
background: red;
}
jQuery
$('#data tr').click(function(e) {
$('#data tr').removeClass('highlighted');
$(this).toggleClass('highlighted');
});
Demo: http://jsfiddle.net/jrthib/HVw7E/2/
in your css:
.selected{
background: #F00;
}
in the jquery:
$("#data tr").click(function(){
$(this).toggleClass('selected');
});
Basically you create a class and adds/removes it from the selected row.
Btw you could have shown more effort, there's no css or jquery/js at all in your code xD
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With