Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
188
rated 0 times [  191] [ 3]  / answers: 1 / hits: 113050  / 11 Years ago, wed, july 17, 2013, 12:00:00

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>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
<tr>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
<td>&nbsp;</td>
</tr>
</table>

</body>

</html>

More From » jquery

 Answers
20
.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.


[#76930] Tuesday, July 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
leog

Total Points: 225
Total Questions: 113
Total Answers: 118

Location: Oman
Member since Wed, Apr 12, 2023
1 Year ago
;