user2571510
user2571510

Reputation: 11377

jQuery: how to use comma as separator for .each loop

I am using the following to loop through all fields with a specific class and add their values to a variable. This works fine so far.

What is the best / fastest way to add a comma as a separator between the values in the variable here BUT avoid having a comma at the beginning or the end of the variable's content ?

The content of the variable in the end should look like this: value1,value2,value3, ...

My function:

var myVariable = '';

$('.myClass').each(function()
{
    myVariable += $(this).val();
})

Thanks for any help with this, Tim.

Upvotes: 3

Views: 3348

Answers (2)

Adil
Adil

Reputation: 148110

You can use jQuery map(), also use this.value instead of $(this).val().

$('.myClass').map(function(){
    return this.value;
}).get().join(',');

Edit Based on comments

var myVariable = $('.myClass').map(function(){
    return this.value;
}).get().join(',');

Upvotes: 5

patel.milanb
patel.milanb

Reputation: 5992

var myVariable = [];
$('.myClass').each(function() {
    myVariable.push($(this).val());
});

var commaSepValues = myVariable.join(','); // add commas between the values...

Upvotes: 4

Related Questions