Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comma separated list in jQuery

I'm trying to create a comma separated list from what is checked on the form.

var $StateIDs = $(':checked');
var StateIDs = '';
for (i=0, j = $StateIDs.length; i < j; i++) {
    StateIDs += $StateIDs[i].val();
    if (i == j) break;
    StateIDs += ',';
}

There's probably a 1-liner that can do this, or a single function.

like image 787
Phillip Senn Avatar asked Apr 26 '11 18:04

Phillip Senn


People also ask

How can use comma separated value in jQuery?

By using split() function in we can split string with comma or space etc. based on requirement in jQuery.

How to get comma separated values from list in JavaScript?

Answer: Use the split() Method You can use the JavaScript split() method to split a string using a specific separator such as comma ( , ), space, etc. If separator is an empty string, the string is converted to an array of characters.

How do you add comma separated values in an array?

The comma separated list can be created by using implode() function. The implode() is a builtin function in PHP and is used to join the elements of an array. implode() is an alias for PHP | join() function and works exactly same as that of join() function.

How to split comma separated values to array in JavaScript?

Method 1: Using split() method The split() method is used to split a string on the basis of a separator. This separator could be defined as a comma to separate the string whenever a comma is encountered. This method returns an array of strings that are separated.


1 Answers

map() is going to be your friend here.

var StateIDs = $(':checked').map(function() { 
    return this.value; 
}).get().join(',');

StateIDs will be a comma-separated string.


Step-by-step - What is going on?

$(':checked')
// Returns jQuery array-like object of all checked inputs in the document
// Output: [DOMElement, DOMElement]

$(':checked').map(fn);
// Transforms each DOMElement based on the mapping function provided above
// Output: ["CA", "VA"]  (still a jQuery array-like object)

$(':checked').map(fn).get();
// Retrieve the native Array object from within the jQuery object
// Output: ["CA", "VA"]

$(':checked').map(fn).get().join(',');
// .join() will concactenate each string in the array using ','
// Output: "CA,VA"
like image 139
John Strickler Avatar answered Oct 08 '22 10:10

John Strickler