Monicka Akilan
Monicka Akilan

Reputation: 1549

iterate a map in for loop in jquery

Hi am using a ajax call to get a map. Its working fine. I want to display the map value in a table only two td allowed remaining will move to next row

My code is here

My output is like this

enter image description here

I want to make this as two td per tr

s = s + "<tr class='fc-staff'>";
$.each( msg, function( key, value ) {
  alert( key + ": " + value );
   s = s + "<td >" + value
    + "</td> ";
});

Its working fine but all the values are in single tr. I want something like this

for ( var j = 0; j < limit; j += 2) {
s = s + "<tr class='fc-staff'>";
for ( var i = j; i < j + 2; i++) {
  alert("value " + i + "/" + j+" val :"+msg[i,value]);
    if (msg[i] != undefined) {  
s = s + "<td >" + msg[i,value]
    + "</td> ";
}
}
    s = s + "</tr>";

Note: The above code i tried for list working fine as i except but dont know to do with map. Please help me

Upvotes: 1

Views: 2683

Answers (3)

Bas van Dijk
Bas van Dijk

Reputation: 10713

If I understand you correct you want to iterate through the key/value pairs and put all the values in separated td's which. These td's you want in a tr. You could try something like:

var html;

var tr = $("<tr/>");

$.each( msg, function( key, value ) {

    tr.append($("<td/>").html(value));

});

html += tr.html();

Upvotes: 1

tewathia
tewathia

Reputation: 7298

You just need to combine the two approaches. Here's a working fiddle.

s = "<tr class='fc-staff'>";
var count = 0;
$.each(msg, function(key, value) {
    if (count > 1 && count % 2 === 0) {
        s += "</tr><tr class='fc-staff'><td>" + value + "</td>";
    } else {
        s = s + "<td >" + value + "</td> ";
    }
    count++;
});

Upvotes: 1

akbar ali
akbar ali

Reputation: 437

You can try this

var counter=0;
s = s + "<tr class='fc-staff'>";
$.each( msg, function( key, value ) {
if(counter<2)
{
   ++counter;
   s = s + "<td >" + value   + "</td> ";
}
else
{
    counter=1;
    s = s + "</tr><tr class='fc-staff'>";
    s = s + "<td >" + value   + "</td> ";
}
});
s = s + "</tr>";

Upvotes: 1

Related Questions