jQuery saves the day, again

I'm a huge fan of jQuery. Call me a fanboi I don't care, I just love it. It's actually one of the main reasons why I wanted to redevelop my site, to convert everything over to jQuery.

Anyway today jQuery's mantra came into play: "Write Less, Do More". I love jQuery for the simplicity and the likeness to CSS in all of it's selecting/traversing glory.

We're working on an application that involved ridiculously huge forms (like, a single form with 150+ form fields). To make the forms more readable we typically stripe each alternating row, making even or odd rows a different color. This is no problem when you're getting a set of records from a database and outputting them, take this example:

HTML / Coldfusion
<cfloop query="getData"> <tr<cfif CurrentRow MOD 2 EQ 0> class="row-even"</cfif>> <td>#DataHere#</td> </tr> </cfloop>

CSS
tr.row-even{ background:#EEE; }

This won't work for a standard form because the form fields are hard-coded into the page. There's nothing to loop through. What we could do, and have done in the past until now, is assign the class manually to each row. So each row would be: <tr class="row-even"> ...

Problem is, down the road the client may will want to reorder the fields or add/remove a form field. This becomes a management nightmare because now you have to reassign the class on every single row. In this case we're talking 150+ rows, not good. So here's a very simple, very straight forward example of the power of jQuery. Take this example:

The jQuery:
<script type="text/javascript"> $(document).ready(function(){ $('.striped tr:even').addClass('row-even'); }); </script>

The HTML:
<table class="striped"> <tr> <td>Form Field</td> </tr> <tr> <td>Form Field</td> </tr> <tr> <td>Form Field</td> </tr> <tr> <td>Form Field</td> </tr> </table>

If you're not at all familiar with jQuery you can read here to find that the document.ready portion is simply waiting for the document to load before running.

A common task in jQuery is adding or removing classes. In the example above you can clearly follow the css-style selectors/syntax that jQuery uses. First it looks for a class of striped (in this case, we gave our table a class of striped). Then using the :even selector we are getting all even rows and adding a class using .addClass.

It's really that simple, jQuery counts the rows up, adds the class accordingly and voila! This is something I will definitely use from now on.

Btw, go buy the book, that's where I learned this little nugget!

Comments    

02.20.2008   Alister Cameron // Blogologist
Amen to the jQuery love.

Came to your blog via the ping.fm widget post, which I've now installed.

Yay!
02.20.2008   jyoseph
Awesome!

Leave One

  • Required fields are marked with an asterisk *

Tags
Share
Back Up   |   Blog Feed