views:

724

answers:

1

Hello,

I'm attempting to iterate through a response from a jQuery Ajax request (returned as XML).

With that response, I'm building an HTML table with 3 columns (capable of an unlimited number of rows). Once the 4th XML node/ "company" is found, it should start a new row in the table. Any help with the JS to determine when the new row should be added is most appreciated. Thanks!

JS example:

/* jQuery Ajax Call here */

success: function(xml){  
    var trow = $("<tr>");  
    $(xml).find("Company").each(function(index){  
    var cellData = "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
"<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+ $(this).attr("Name")+ "</a></div>"+  
"<div class=\"description\">"+ $(this).attr("Description") + "</div></div></div></td>";  
    $(cellData).appendTo(trow);   
      });  
      trow.appendTo('#tbl');  
    }  
  });  

});

Example XML response from web service:

<Companies>
    <Company ID="6" Name="Company name 1" Description="Lorem ipsum" />
    <Company ID="22" Name="Company name 2" Description="Lorem ipsum" />
    <Company ID="28" Name="Company name 3" Description="Lorem ipsum" />
    <Company ID="31" Name="Company name 4" Description="Lorem ipsum" />
</Companies>
+2  A: 

The modulo operator is great for things like this. Basically it divides one number by another number and returns the remainder. So 1 % 4 = 1 and 4 % 4 = 0 and 8 % 4 = 0:

success: function(xml){
    var trow = $("<tr>"), table = $("#tbl");  
    $(xml).find("Company").each(function(index){  
        var cellData =  "<td width=\"33%\" valign=\"top\" ><div class=\"container\">"+
                        "<div class=\"item\"><a href=\"#\" title=\"\" target=\"\">"+ 
                        $(this).attr("Name")+ "</a></div>" +  
                        "<div class=\"description\">" + $(this).attr("Description") + 
                        "</div></div></div></td>";
        $(cellData).appendTo(trow);   
        if( (index + 1) % 4 == 0) {
            trow.appendTo(table);
            trow = $("<tr>");
        }

      });  
      if(trow.is(':not(:empty)')) trow.appendTo(table);  
    }  
    });
});

I also stored $("#tbl") in a variable to reduce the number of lookups.

Doug Neiner
Thank you so much for such a prompt response! Ah, brilliant use of the modulo operator. I've been wrapping up this solution for quite a few hours now. The only thing I tweaked was the "4==0" to "3==0" to force the 4th result to start a new table row. Again, I appreciate your help!
jryan
Happy to help! Glad you caught that the `4 == 0` should have been a 3.
Doug Neiner