Skip navigation

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>&nbsp;</td>
   <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
  </tr>
  <tr>
    <td>&nbsp;</td>
    <td>&nbsp;</td>
    <td>&nbsp;</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>
About these ads

3 Comments

  1. Very good tip! Thanks!

  2. 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″);

    });

  3. 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″);

    });


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 150 other followers

%d bloggers like this: