Tuesday, December 21, 2010

styling tables made easy with DataTables jQuery plugin

In the past I've usually formatted results into a table using 'zebra' styling where each alternating row would be shaded with a different background color. Below is an example:




Typically the JSP would look as follows:


<table cellspacing="0" class="tracker-summaries">
    <tr>
        <th>Procedure</th>
        <th class="right-col">Version</th>
        <th class="right-col">Date added</th>
        <th class="right-col">Filename</th>
        <th class="right-col">&nbsp;</th>
    </tr>
    
    <c:set var="rownum" value="0" />    
<c:forEach items="${procedures}" var="procedure" >
                
        <c:set var="rownum" value="${rownum + 1}" />
        <tr <c:if test="${rownum mod 2 == 1 }">class="odd"</c:if>>
            
            <td>${procedure.type.value }</td>
            <td class="right-col">${procedure.version }</td>
            <td class="right-col">
                <c:if test="${not empty procedure.dateCreated}">
                    <fmt:formatDate pattern="dd/MM/yyyy" value="${procedure.dateCreated}" />
                </c:if>
            </td>    
            <td class="right-col">                
                ${ procedure.filename }
            </td>
            <td class="right-col">
                <a href='<c:url value="/inventory/inventoryDocDownload.html" />?<%= ParamNames.TYPE %>=<%=InventoryDocDownloadController.TYPE_PROCEDURE%>&id=${procedure.id}'>Download</a>
            </td>
        </tr>    
            </c:forEach>

</table>

As highlighted in red, I would manually assign each alternating row a different style to achieve the 'zebra' look and feel. This worked fine, but it became quite repetitive when you have multiple pages listing results in tables.

I recently, discovered a much better solution without having to customize each JSP that contained tabular results, using a jQuery plugin called DataTables

It's really quite simple. You create your tables without any styling attached. Then invoke a few lines of jQuery code to apply styling dynamically as follows:


    <script type="text/javascript">

        $(document).ready(function() {
            oTable = $('table.display').dataTable({
                "bJQueryUI": true,
                "bPaginate": false,
                "bLengthChange" : false,
                "bFilter" : false                            
            });

            $(".ui-toolbar:first").css('display','none');            
        } );        
    
    </script>

If you can apply this to every header to of your page, then all your pages will automatically have their tables properly formatted.

Furthermore, your tables will automatically have sorting, searching and pagination built-in.

No comments:

Post a Comment