I’m using jQuery 1.4. I’m trying to highlight the <td> tag of a Table everytime that a radio button inside that "<td>" is selected and remove the highlight class if it’s not selected.
Here’s the mark-up:
CSS:
.highlight-blue { background-color: #81BEF7; }
<table id="tblContainer">
<tr>
<td>
<input type="radio" name="book" value="book1" /> Book 1</td>
<td>
<input type="radio" name="book" value="book2" /> Book 2</td>
<td>
<input type="radio" name="book" value="book3" /> Book 3</td>
<td>
<input type="radio" name="book" value="book4" /> Book 4</td>
</tr>
</table>
Javascript:
// highlight checked radion button
$('#tblContainer :radio').click(function() {
//add class to hilghlight selected radio button
var cell = $(this).closest('td');
if ($(this).is(':checked')) {
cell.addClass('highlight-blue');
}
else {
//remove highlight class
cell.removeClass('highlight-blue');
}
});
The problem is that it doesn’t remove the class from the previous selected radio buttons.
Update 1: See new updated mark-up here http://jsbin.com/egusud/7
Yes, you’ll want to go up to the row level (if the radio buttons are just related to each other in the row) or table level (if they’re related to each other across rows).
Assuming only within row (live example):
Note that you only get a click on a radio button if it’s the selected one, so no need to check.
Off-topic: Those radio buttons will be easier for people to click if you add
labels (live copy):If so, you might want to add this CSS style to the labels (live copy):
…to make it more obvious that they can be clicked.
Update: From the comments, it appears your radio buttons are in different rows from each other, and that you have other radio buttons mixed in as well, like this:
In which case, to remove the class from the old one, you just have to find the other radio buttons with the same names, then their parent cells with that class (live copy):
Or alternately, the “marker class” approach (here I’ve used “rb-” plus the radio button’s name, but you’ll want to be sure the radio button names are valid for class names) (live copy):