views:

29

answers:

3

This should be really simple but I'm a javascript/jQuery rookie, so here we go:

With the following code I can select a certain element

var user = $(".ui-selected .user-name").html();

But if there are multiple elements with the above classes, only the first value gets selected. What I would like to accomplish is a variable with all the elements seperated by a , like: user1,user2,user3 ... etc. Any help would be greatly appreciated, thanks in advance!

+3  A: 

You can use .map() to get an array of values, then .join() them to a string, like this:

var usersString = $(".ui-selected .user-name").map(function() {
                    return $(this).html(); //or this.innerHTML
                  }).get().join(',');

Edit: here's a demo, you can tweak the join, etc if needed.

Nick Craver
A: 

You can use .each() to go through each one:

$(".ui-selected .user-name").each( function(){
    var user = $( this ).html();
    // do stuff
} )
hookedonwinter
A: 

You can do something like this:

var myElements = "";
$(".ui-selected .user-name").each( function(){
   myElements += $(this).html() + ",";
} )
VinTem
You'll end up with a dangling comma at the end that you'll need to truncate. Better (in my opinion) to push items into an array, and `.join(',')`, or have jQuery build the array with `.map()`.
patrick dw