user2738640
user2738640

Reputation: 1227

jQuery .each: Do not add comma in last field

I want to get values of all fields in a variable separated by a comma. For example: 1,2,3

The following code will work fine, but it only adds the comma at end of the last value also. How can I remove that?

fields = $('.wrap').find('.text');
var data = '';

fields.each(function() {
    var value = $(this).val();  
    if ( value != '' ) {
        data += ' ' + value + ',';
    }   
});

alert(data);

JSFiddle: http://jsfiddle.net/cn5Gt/

Upvotes: 2

Views: 7935

Answers (7)

nnnnnn
nnnnnn

Reputation: 150020

How about something like this:

var data = $('.wrap').find('.text')
                     .map(function(i,el){ return el.value || null; })
                     .get().join(", ");

Demo: http://jsfiddle.net/cn5Gt/11/

jQuery's .map() method will "Pass each element in the current matched set through a function, producing a new jQuery object containing the return values." You can still include your if ( value != '' ) { test in the callback function because if your function returns null or undefined then .map() will not use that particular value. (I've used || null above as a shortcut to an if/else structure.)

Call .get() (or .toArray()) on the result and you'll have an actual array, which means you can then use the Array .join() method to form a string with the values comma separated.

If you need to do other processing on each item besides just getting the value you could stick with the .each() loop and add the values to an array that you then join after the loop (like some of the other answers), or just use the string .slice() method to remove the trailing comma and space characters.

Upvotes: 1

Rasmus Stougaard
Rasmus Stougaard

Reputation: 433

Try this:

Using the length function to determine the position of the each

    

    var fields = $('.wrap').find('.text');
    var len    = fields.length;

    var data = '';

    fields.each(function(index, element) {

        var value = $(this).val();  
        if ( value != '' ) {
            data += ' ' + value;
            if (index != len - 1) {
                data += ',';
            }
        }

    });

    alert(data);

Upvotes: 0

mmisiarek
mmisiarek

Reputation: 191

You can push elements on array than just use join() method.

fields = $('.wrap').find('.text');

var data = [];

fields.each(function() {
    var value = $(this).val();  
    if ( value != '' ) {
        data.push(value);
    }   
});

alert(data.join());

Upvotes: 3

HIRA THAKUR
HIRA THAKUR

Reputation: 17757

Simplest of all:just replace your last line with the below line

 alert(data.slice(0,-1));//where data is string

http://jsfiddle.net/cn5Gt/7/

DOC MDN : slice

Upvotes: 1

Duncan McArdle
Duncan McArdle

Reputation: 521

You could just remove the final character afterwards?

data = data.substr(0, data.length - 1);

http://jsfiddle.net/cn5Gt/3/

Upvotes: 1

Christof
Christof

Reputation: 3927

I always use arrays for these kind of things:

var fields = $('.wrap').find(".text[value!='']");
var data = [];

fields.each(function() {
    data.push($(this).val());
});

alert(data.join(','));

Upvotes: 6

Mark Walters
Mark Walters

Reputation: 12390

Try the code below, using the i which is the loop index and test against the length of the jQuery object.

fields = $('.wrap').find('.text');
var length = fields.length;
var data = '';

fields.each(function(i) {
    var value = $(this).val();  
    if ( value != '' ) {
        if(i === length-1) {  //The last one
            data += ' ' + value;
        } else {
            data += ' ' + value + ',';
        } 
    }   
});

Updated fiddle

Upvotes: 2

Related Questions