jQuery change background color of table row when selecting a checkbox
15,164
Solution 1
You want the row highlighted? Use the .closest() method to grab the row element, then add a highlighting class to it: http://jsfiddle.net/etVc8/3/
$(function() {
$('td:first-child input').change(function() {
$(this).closest('tr').toggleClass("highlight", this.checked);
});
});
Solution 2
<input type="checkbox" onclick='highlight(this)'> 1<br>
<input type="checkbox" onclick='highlight(this)'> 2<br>
<input type="checkbox" onclick='highlight(this)'> 3<br>
<script>
function highlight(obj){
$(obj).parent().parent().css("background","#000");
}
</script>
Author by
Paramasivan
Updated on July 08, 2022Comments
-
Paramasivan almost 2 years
I have 5 columns in a table. Column 1 has a check box named name="strurl1", name="strurl2", name="strurl3" , etc. If selected the table row background color is to change from #f1f1f1 to #e5e5e5 .
I tried but the code is not working.
The main css is
.overviewtable tbody tr td { line-height:normal; border-top:1px solid #FFF; border-bottom:1px solid #c4c4c4; height:35px; padding-top:10px; padding-bottom:5px; background-color:#f1f1f1; } .overviewtable tbody tr td.col1 { width:316px; padding-left:15px; border-left:4px solid #FFF; font-size:12px; color:#999999; }
The table columns are named col1, col2, col3, col4 and col5.
Any help? Thanks in advance.
-
Paramasivan over 12 yearsI have specified the background color in tbody tr td as below: .overviewtable tbody tr td { line-height:normal; border-top:1px solid #FFF; border-bottom:1px solid #c4c4c4; height:35px; padding-top:10px; padding-bottom:5px; background-color:#f1f1f1; } If I mention as $(function() { $('td:first-child input').change(function() { $(this).closest('table.overviewtable tbody tr td').toggleClass("highlight", this.checked); }); }); then only the first column containing the checkbox is highlighted.
-
Fawad Ghafoor almost 12 yearswhat if i have a checkbox in <th> of a Table that Check/uncheck all checkboxes ??
-
rkw almost 12 years@FawadGhafoorasXaineeKhan: there are a myriad of ways to handle that, for me, I prefer having the event triggered:
$('th:first-child input').change(function() { $('td:first-child input').trigger('change'); }