Thursday, April 23, 2009

Formatting HTML Table Rows With Javascript

If we are working with PHP we can easily formatting even and odd table row's color with looping. But, what if we are working with the pure HTML table? Can we format even and odd row with different color without typing it manually inside the <tr> tag? Yes, we can. Just use Javascript to do that job.

The basic concept is we must loop through the all of the rows of an HTML table that we want to format and then add the class attribute for each row. That class attribute will contain the name of CSS class for an even or odd row.

Sample Code

This the sample code.

<html>
<head>
    <title>Table</title>
    <style type="text/css">
        /* DEFINE THE CSS CLASSES */
        .table_header{
            background-color:#AAAAAA;
            color:#FFFFFF
        }
        
        .even{
            background-color:#DDDDDD;
        }
        
        .odd{
            background-color:#EEEEEE;
        }
        
        #table1{
            background-color:#777777;
        }
    </style>
    <script language="javascript" type="text/javascript">
        /* THIS IS THE FUNCTION FOR FORMATTING ROW */
        function formatRow(table_id){
            var table=document.getElementById(table_id);
            for(var i=1;i<table.rows.length;i++){
                var className="";
                if(i%2==0){
                    className="even";
                }
                else{
                    className="odd";
                }
                
                table.getElementsByTagName("tr")[i].className=className;
            }
        }
    </script>
</head>
<body>
    <table width="300" id="table1" border="0" cellspacing="1">
        <tr class="table_header"><th>&nbsp;</th><th>&nbsp;</th><th>&nbsp;</th></tr>
        <tr><td>&nbsp;</td><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>
        <tr><td>&nbsp;</td><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>
        <tr><td>&nbsp;</td><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>
        <tr><td>&nbsp;</td><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>
    <script language="javascript">
        /* FORMAT THE TABLE */
        formatRow("table1");
    </script>
</body>
</html>

How Does It Look Like?


No comments: