[DisplayTag] Changing a row's CSS class based on values in the row.
One request I've seen on the displaytag-user list a few times is the ability to change a <tr>'s CSS class based on a certain value. While the displaytag doesn't have this feature out-of-the-box, it is possible (and fairly easy) to do. All you need to do is sprinkle a little JavaScript into the mix. Basically, the displaytag will render a well-formed HTML table - like the following:
Username | First Name | Last Name |
---|---|---|
mraible | Matt | Raible |
tomcat | Tomcat | User |
By adding an "id" attribute to your table (i.e. id="user"), your table will get an "id" attribute and now you can easily access it via the DOM. The following JavaScript will grab the table and search the first column for a value of 'mraible' - and if found, it will change the row's background color to red.
<script type="text/javascript"> <!-- var table = document.getElementById("user"); var tbody = table.getElementsByTagName("tbody")[0]; var rows = tbody.getElementsByTagName("tr"); // add event handlers so rows light up and are clickable for (i=0; i < rows.length; i++) { var value = rows[i].getElementsByTagName("td")[0].firstChild.nodeValue; if (value == 'mraible') { rows[i].style.backgroundColor = "red"; } } //--> </script>
You could easily change rows[i].style... to rows[i].className = if you want to assign a new CSS class. Now let's see it in action (and see if your browser supports it). This has only been tested in Safari and Mozilla on OS X.
Username | First Name | Last Name |
---|---|---|
mraible | Matt | Raible |
tomcat | Tomcat | User |
Other displaytag tips: Static Headers HowTo and Highlight and allow clicking of rows. The 2nd tip (highlighting) is available in AppFuse, in the userList.jsp page.
BTW, I also added support for the DisplayTag to render the results from JSTL's SQL Tag. I haven't committed it yet - I'm still waiting for more feedback.
Posted by James on March 08, 2004 at 09:53 PM MST #
Posted by Charlie on March 09, 2004 at 09:00 PM MST #
Posted by Ted on March 10, 2004 at 11:33 PM MST #
Ted - Support for the JSTL Result class (a.k.a. Map[] for rows) has been added to CVS. I'm going to update AppFuse with displaytag's latest nightly build and you should be able to checkout a demo at http://demo.raibledesigns.com/appfuse/users.jsp in the next hour or so.
Posted by Matt Raible on March 11, 2004 at 02:06 PM MST #
Posted by Knut Erik Ballestad on March 15, 2004 at 06:04 PM MST #
Posted by bhumit on March 03, 2006 at 03:49 PM MST #
Posted by 220.225.70.2 on November 23, 2006 at 08:45 AM MST #
Posted by sumadha on May 14, 2009 at 12:07 PM MDT #
Posted by Neena on September 21, 2010 at 09:44 AM MDT #
Posted by G. Raaja on May 27, 2011 at 12:27 PM MDT #