tags:

views:

2859

answers:

5

I am working on trying to better understand the jQuery.each() method. Here's an example I came up with, not very practical, but it performs an action on each selected item from the selected set of elements returned:

// Loop over each link.
$( "#links a.number" ).each(

// For each number, run this code. The "intIndex" is the 
// loop iteration index on the current element.
function( intIndex ){

// Bind the onclick event to simply alert the iteration index value.
    $( this ).bind ("click", function(){
        alert( "Numbered index: " + intIndex );
    });
});

What are some examples of practical uses of the .each method you are using in your code? What exactly does $(this) represent?

+1  A: 

A simple use, but it's very handy for iterating over a table and striping alternate rows:

// Adds CSS styling to alternate rows of tables marked with a .data class attribute.
$("table.data").each(function() {
 if (!$(this).hasClass("noStriping")) {
  $(this).find("tbody tr:nth-child(odd)").addClass("odd");
  $(this).find("tbody tr:nth-child(even)").addClass("even");
 }
});
Derek Lawless
i'd rather use $("tr:odd").addClass("odd");
rizzle
This is better done with $('.classname:even').addClass('oddRow').
Turnor
indeed! or $("tr:even").addClass('even');
altCognito
Should be selecting with "tbody tr:odd" - since you generally only want the main data striped, not the head (or foot) sections. You are all structuring your tables with thead/tbody tags, right?
Peter Boughton
Derek, That was the first example that came to my head but as these guys have shown this example can be done easier in other jQuery ways.
RedWolves
+5  A: 

Note there are two types of jQuery's each, the one iterates over and returns jQuery objects, the other is a more generic version.

Core/each
Example: Create a csv of all the hrefs on the page. (iterates over matching DOM elements and 'this' reffers to the current element)

 var hrefs = "";

 $("a").each(function() { 
     var href = $(this).attr('href');
     if (href != undefined && href != "") {
         hrefs = hrefs + (hrefs.length > 0 ? "," + href : href);
     }
 });

 alert(hrefs);

Utilities/jQuery.each
Iterating over an array or the elements of an object: (via: jQuery Documentation)

$.each( { name: "John", lang: "JS" }, function(i, n){
  alert( "Name: " + i + ", Value: " + n );
});

$.each( [0,1,2], function(i, n){
  alert( "Item #" + i + ": " + n );
});
rizzle
@rizzle - I couldn't get your first example to work. Here is how I got it to work in Firebug for this page:var hrefs = "";$( "a" ).each(function(){ var href = $(this).attr('href'); if (href != undefined) { hrefs += hrefs + href.length > 0 ? "," + href : href; }});alert(hrefs);
RedWolves
heh, the error is that i was doing href.length instead of hrefs.length. I check the length to see if i should prepend the comma for the list. sorry i should have tested
rizzle
heh you're right, i had to cater for undefined as well. I've updated the code.
rizzle
A: 

You use the each function to access/modify any dom property that isn't wrapped by jquery.

I often have a grid/table with a column containing checkboxes.

I write a selector to get the list of checkboxes, then set the checked property to true/false. (for check all, uncheck all).

You have to use the each function for that.

$(".mycheckbox").each(function() { this.checked = true; });

Chris Brandsma
Can't you do $(".mycheckbox").attr('checked',true); ?
Peter Boughton
@Peter, along those lines, i've had better luck with $(".mycheckbox").attr('checked','checked');
rizzle
+3  A: 

I sometimes use it for traversing a large number of subelements in an XML data resultset

   my parsedData = [];  
   $('result', data).each(function() {
      parsedData.push(  
         { name: $('name', this).text(),
           addr: $('addr', this).text(),
           city: $('city', this).text(),
           state: $('state', this).text(),
           zip: $('zip', this).text()
      });

That works pretty nicely.

altCognito
I've not seen this structure before - is the second argument a set of XML nodes?
Peter Boughton
Heh, yep - the second argument is the 'context', which defaults to current document, but can actually be any DOM or document. ( http://docs.jquery.com/Core/jQuery ) Handy. :)
Peter Boughton
This is cool. Like Peter I needed to figure out what was going on. What exactly is push? A array method to add to the array?
RedWolves
Yeah, push is a native JS func for arrays. For each of the "result" elements of the XML, it pushes into the array the object being created. By using "this" in the context argument of .each, some time is saved parsing the document. Handy if you have lots of flattening/filtering in an XML doc to do.
altCognito
Another way to put it: push is pretty much the same as: myarray[myarray.length] = something; (but nicer). Array.shift also comes in handy at times.
altCognito
Cool thanks for the explanation.
RedWolves
+1  A: 

I use the .each() method for ASP.NET WebMethod calls that return JSON strings. In this example, it populates a listbox with the values returned from the Ajax call:

async: true,
type: "POST",
url: "Example.aspx/GetValues",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
  var list = $('<select />');

  $.each(data.d, function(){
       var val = this.Value;
       var text = this.Text;
       list.append($('<option />').val(val).text(text));
  });

  $('#listbox').empty().append(list.find('option'));
},

ASP.NET has a built-in JSON serializer that automagically converts a class into the JSON string you see at the bottom of this post. Here is an example class that can be returned by the WebMethod:

public class Tuple
{
    public string Text;
    public int Value;

    public Tuple(string text, int val)
    {
        Text = text;
        Value = val;
    }
}

And the WebMethod itself:

[WebMethod]
public static List<Tuple> GetValues()
{
    List<Tuple> options = new List<Tuple>();
    options.Add(new Tuple("First option", 1));
    options.Add(new Tuple("Second option", 2));
    return options;
}

When you specify dataType: "json" in the jQuery Ajax options, the string is automatically converted into a Javascript object, so you can simply type this.Text or this.Value to get the data.

Here is the resulting JSON returned from the WebMethod above:

{"d":[{"Value":1,"Text":"First option"},{"Value":2,"Text":"Second option"}]}

Note: the data.d parameter (and likewise the first value seen in the JSON string) is explained here.

John Rasch
Yeah this is a cool practical example. I like it. Can you edit it with a sample JSON example? I assume Value and Text are variables in your JSON?
RedWolves