javascript - Loop through JSON array, display two and then Count -


okay, i'm json noob basic jquery knowledge , i've looked on solution , can't find one. appreciated.

i need to:

1) loop through json array (working)

2) display first 2 results "mbrname"

3) display count rest of results.

i looping through , displaying mbrname results. somehow need display first 2 , if there more display "+ # others"

here's screenshot of final product should like: enter image description here

here's code produces now: enter image description here

here's json:

{  "messages":{   "message":[      {         "date-time":"june 2, 2013 12:22 pm",         "subject":"this message subject",         "msg-string":"001",         "newmsg":"true",         "attach":"shop-cart",         "recipient":[            {               "mbrname":"d. craig",               "mbr-href":"#craig"            },            {               "mbrname":"n. mccoy",               "mbr-href":"#mccoy"            },            {               "mbrname":"j. smith",               "mbr-href":"#smith"            },            {               "mbrname":"b. wardlaw",               "mbr-href":"#wardlaw"            }         ]      },      {         "date-time":"may 23, 2013 12:22 pm",         "subject":"this great subject",         "attach":"none",         "msg-string":"002",         "newmsg":"true",         "recipient":[            {               "mbrname":"d. craig",               "mbr-href":"#craig"            },            {               "mbrname":"n. mccoy",               "mbr-href":"#mccoy"            }         ]      },      {         "date-time":"may 11, 2013 12:22 pm",         "subject":"interested in tomatoes",         "attach":"shop-cart",         "msg-string":"003",         "newmsg":"false",         "recipient":[            {               "mbrname":"j. smith",               "mbr-href":"#smith"            }         ]      }   ]  } } 

here's jquery "mbrname" section pulls in names , appends them html:

$.each (message.recipient, function (message, recipient) { var mbrpart = recipient.mbrname + ', '; var currentuser = $('#' + newid + ' .name');  $(currentuser).append(mbrpart);  }); 

thanks in advance help!

i'd keep simple, no need looping:

var recipientstring = message.recipient[0].mbrname; var count = message.recipient.length;  if (count > 1)     recipientstring += ', ' + message.recipient[1].mbrname;  if (count > 2)     recipientstring += ' + ' + (count - 2) + ' others';  $('#' + newid + ' .name').append(recipientstring); 

Comments

Popular posts from this blog

apache - Remove .php and add trailing slash in url using htaccess not loading css -

javascript - jQuery show full size image on click -