tags:

views:

6950

answers:

3

I'm giving a presentation to some coworkers today on how to use jQuery with ColdFusion. This is more of an introduction to jQuery than an advanced session. I'm trying to show how one can loop using jQuery's $().each() method, and in trying to come up with some practical, real world examples and I've drawn a blank. Any suggestions?

+4  A: 

Skip it. It'd be confusing to the new users, anyhow. jQuery returns arrays of objects and applies function calls to each already, which isn't obvious to the noob. You'll spend time on each() and all you'll get from it is people who do $('a').each().css("color", "red"); or $('a').each(function(){ $(this).css("color", "red");});

Don't ask how I know noobs encountering .each() might end up making this mistake.

Will
depends what language you are coming from. in ruby, .each is the preferred way of doing a foreach loop.
Matt Briggs
There are several valuable uses of the .each() method that you can't do with just a selector. Granted, it's almost always best to use just selectors if possible, but, this its not always feasible. Matt Briggs presents a very practical use case where using only a selector would be basically impossible (without creating your own selector... in which case you'd probabaly use .each() in that).
KyleFarris
+9  A: 
// changes every other div green
$("div").each(function(i) { if (i % 2) this.style.backgroundColor = "green"; });
Matt Briggs
+2  A: 

Check all checkboxes in a datagrid based on the value of some external checkbox

$('#<%=dgMyDataGrid.ClientID %> :checkbox').each(function(i)
{
this.checked = $(#SelectAll).is(":checked")
});

I originally had a code behind findcontrol() method in place of the #SelectAll, but this hopefully illustrates what I was trying to do. This function was also bound to the click event of #SelectAll.

(also let it be noted that I am a jQuery newbie!)

edit: full implementation of what I used this for is here if anyone is interested :)

Zeus
This is a great example! Thanks!
Hooray Im Helping
Hooray I'm helping! :) added a link to the code as I used it if you're interested.
Zeus