Creating alternating row colors on a table in ColdFusion

Readability

Creating alternating row colors on a table in ColdFusion

The fol­low­ing exam­ple shows how you can add alter­nat­ing row col­ors on an HTML table in Cold­Fu­sion by loop­ing over a data­base query and using the query currentRow attribute and the MOD oper­a­tor to deter­mine if the cur­rent row num­ber is “odd” or “even”.


    SELECT *
    FROM ORDERS
    ORDER BY ORDERDATE DESC





    
ID: NAME: DATE: TOTAL (USD):
#getOrders.ORDERID# #getOrders.CUSTOMERLASTNAME#, #getOrders.CUSTOMERFIRSTNAME# #dateFormat(getOrders.ORDERDATE)# #dollarFormat(getOrders.TOTAL)#

And the out­put of the <CFOUT­PUT> tag is as fol­lows:
CFQUERY currentRow MOD 2

Or, instead of using a <CFIF> and <CFELSE> block, you could use the iif() and de() func­tions, as seen in the fol­low­ing snippet:



    #getOrders.ORDERID#
    #getOrders.CUSTOMERLASTNAME#, #getOrders.CUSTOMERFIRSTNAME#
    #dateFormat(getOrders.ORDERDATE)#
    #dollarFormat(getOrders.TOTAL)#


The following example shows how you can add alternating row colors on an HTML table in ColdFusion by looping over a database query and using the query currentRow attribute and the MOD operator to determine if the current row number is “odd” or “even”.

<cfquery name="getOrders" datasource="cfartgallery">
    SELECT *
    FROM ORDERS
    ORDER BY ORDERDATE DESC
</cfquery>
 
<style>
    .odd {
        background-color: #EEEEEE;
    }
    .even {
        background-color: #FFFFFF;
    }
</style>
 
<table>
    <tr bgcolor="#CCCCCC">
        <th>ID:</th>
        <th>NAME:</th>
        <th>DATE:</th>
        <th>TOTAL (USD):</th>
    </tr>
    <cfoutput query="getOrders">
    <tr class="<cfif (getOrders.currentRow MOD 2 EQ 0)>even<cfelse>odd</cfif>">
        <td align="center">#getOrders.ORDERID#</td>
        <td><strong>#getOrders.CUSTOMERLASTNAME#</strong>, #getOrders.CUSTOMERFIRSTNAME#</td>
        <td>#dateFormat(getOrders.ORDERDATE)#</td>
        <td align="right">#dollarFormat(getOrders.TOTAL)#</td>
    </tr>
    </cfoutput>
</table>

And the output of the <CFOUTPUT> tag is as follows:
CFQUERY currentRow MOD 2

Or, instead of using a <CFIF> and <CFELSE> block, you could use the iif() and de() functions, as seen in the following snippet:

<cfoutput query="getOrders">
<tr class="#iif((getOrders.currentRow MOD 2 EQ 0), DE('even'), DE('odd'))#">
    <td align="center">#getOrders.ORDERID#</td>
    <td><strong>#getOrders.CUSTOMERLASTNAME#</strong>, #getOrders.CUSTOMERFIRSTNAME#</td>
    <td>#dateFormat(getOrders.ORDERDATE)#</td>
    <td align="right">#dollarFormat(getOrders.TOTAL)#</td>
</tr>
</cfoutput>

One thought on “Creating alternating row colors on a table in ColdFusion”

  1. A simpler way would be to name your css classes Row0 and Row1

    Then in your row the class attribute would be:

    regards,
    larry

Leave a Reply

Your email address will not be published.