Set Alternate Table Row Colour using JQuery C# VB.Net Asp.Net

In many cases we need to represent data in tabular format so that user can easily read data in straightforward way. It will be more helpful for users if we can give or set different row color for alternate rows of the table to distinguish one row from another. To do that i have googled and found some examples. But each example will not consider the header row of the table. I need to color alternate rows except header row. So i tried to write a JQuery method which will color alternate rows of a table except considering header row and i want to share with you.

First Add an JQuery Reference:

<script src="Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>

To do the example first create the table and of-course give an id for header row to distinguish header row in JQuery method like below:

    <caption>Article History</caption>
    <thead><tr id="Header"><th>Article</th><th>Published</th></tr></thead>
    <tr><td>An introduction to JQuery</td><td>May 01, 2010</td></tr>
    <tr><td>How to set TextBox Value using JQuery</td><td>May 03, 2010</td></tr>    
    <tr><td>How to color Alternate Row</td><td>May 05, 2010</td></tr>    
    <tr><td>How to declare Variable in JQuery</td><td>May 07, 2010</td></tr>    
    <tr><td>What is JQuery $ Symbol</td><td>May 09, 2010</td></tr>        

And the JQuery method will be:

<script language="javascript">
            $(document).ready(function() {
                $("caption").css("text-align", "left");
                $('#Header').css("background-color", "Red");
                // You can also add css like:
                $("tr:not(\'#Header\'):even").css("background-color", "Blue");
                $("tr:not(\'#Header\'):odd").css("background-color", "Green");

Here i also described how you can apply direct CSS as well as cssclass using JQuery.

The code is self explanatory except filter option. The filters “even” and “odd” can be used in jQuery for selecting odd or even index of the elements. Its an inbuilt option in JQuery library.

Now run the page and hope you will get the below interface:

Hope it will help you.

Download Code Example C#        Download Code Example VB.Net

Leave a Reply

Your email address will not be published. Required fields are marked *

AlphaOmega Captcha Classica  –  Enter Security Code