Tuesday, May 11, 2010

Set alternate table row color using JQuery




Please visit my new Web Site https://coderstechzone.com



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. 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.







To do the example first create the table and definitely give an id for header rows to distinguish header row in JQuery method like below:
<table>
    <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>        
    </table>

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:
                $('#Header').addClass('abc');
                $("tr:not(\'#Header\'):even").css("background-color", "Blue");
                $("tr:not(\'#Header\'):odd").css("background-color", "Green");
            });
    </script>

Here i showed 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.

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

JQuery alternate row color

Hope it will help you.

0 comments:

Want to say something?
I WOULD BE DELIGHTED TO HEAR FROM YOU

Want To Search More?
Google Search on Internet
Subscribe RSS Subscribe RSS
Article Categories
  • Asp.net
  • Gridview
  • Javascript
  • AJAX
  • Sql server
  • XML
  • CSS
  • Free Web Site Templates
  • Free Desktop Wallpapers
  • TopOfBlogs
     
    Free ASP.NET articles,C#.NET,VB.NET tutorials and Examples,Ajax,SQL Server,Javascript,Jquery,XML,GridView Articles and code examples -- by Shawpnendu Bikash