Add this into your head section
<script type="text/javascript" src="includes/jquery-1.3.2.min.js"></script>
Add this into your body section
<table width="500" border="1" cellspacing="0" cellpadding="4">
<tr>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
<p>
<input value="First Column" />
<input id="secondColumn" value="Second Column" />
<input value="Third Column" />
<input value="Reset" />
</p>
<script>
$(function(){
// Change first column background color.
$("#firstColumn").click(function(){
$("table tr td:first-child").css("background-color","#ff0000");
});
// Change second column background color.
$("#secondColumn").click(function(){
$("table tr td:nth-child(2)").css("background-color","#ff0000");
});
// Change third column background color.
$("#thirdColumn").click(function(){
$("table tr td:last-child").css("background-color","#ff0000");
});
// reset background color.
$("#reset").click(function(){
$("table tr td").css("background-color","transparent");
});
})
</script>
3 Comments
Very good tip! Thanks!
However, the easiest way is to give each column (i.e. each TD in a particular column) a specific class and just select those…
function changeColumnBG(index, color) {
$(“table tr”).each(function() {
$(this).find(“td:nth-child(” + index + “)”).css(“background-color”,color);
});
}
$(“#myButton”).click(function() {
changeColumnBG(0,”#ff0000″);
});
The function below helps to keep you from having to duplicate code. I also fixed a bug from my previous post.
However, the easiest way is to give each column (i.e. each TD in a particular column) a specific class and just select those…
function changeColumnBG(index, color) {
$(“table tr”).each(function() {
$(this).find(“td:nth-child(” + index + “).css(“background-color”,color);
});
}
$(“#myButton”).click(function() {
changeColumnBG(0,”#ff0000″);
});