J215D J215D - 1 year ago 121
jQuery Question

concatenating strings in .each loop

This may be a dumb question but I can't seem to get it or find it anywhere.

I have a .each function that returns the id's of a bunch of divs on a page and then assigns them a number. I need them to be outputted in a specific format all as one string so I can pass them to a database and use them as "sort_order" values. (I split them through a sproc in my database).

Here is my code:

jQuery('#updateAllContentButton').click(function() {
var count = 1;
jQuery('.CommentaryItem').each(function() {
var id = GetID(jQuery(this));
var data_str = (id + ':' + count + '~');

So that returns each data_str on a separate line but I need it to return it like this:
144:2~145:3~146:4~147:4~148:5 (so on)

Any help would be appreciated, thanks!

Answer Source

Use map and join :

jQuery('#updateAllContentButton').click(function() {
    console.log(jQuery('.CommentaryItem').map(function(i) {
        return GetID(jQuery(this)) + ':' + (i+1);

Note that you don't have to count yourself : Most jQuery iteration functions do it for you.