4

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 + '~');
        console.log(data_str);
        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!

4 Answers 4

11

Use map and join :

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

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

Sign up to request clarification or add additional context in comments.

1 Comment

This syntax can also be called inside a string concatenation (+).
0

You can use an array for that. Like this...

jQuery('#updateAllContentButton').click(function() {
    var count = 1;
    var arr = [];
 jQuery('.CommentaryItem').each(function() {
    var id = GetID(jQuery(this));
    var data_str = (id + ':' + count + '~');
    arr.push(data_str);
    //console.log(data_str);
    count++;
 });
 console.log(arr.join());
});

Comments

0

try this:

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

});

3 Comments

I mean use += on data_str instead of just = :)
After posting I did try this way but you have to declare data_str before the each loop and it ends up adding an extra ~ at the end.
Yeah, I've corrected that :) Still the best solution is posted by dystroy :)
0

change

var data_str = (id + ':' + count + '~');

to

data_str+ = (id + ':' + count + '~');

full code

jQuery('#updateAllContentButton').click(function() {
    var count = 1,
        data_str;

    jQuery('.CommentaryItem').each(function() {
        var id = GetID(jQuery(this));
        data_str += (id + ':' + count + '~');
        console.log(data_str);
        count++;
    });
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.