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.
By using split() function in we can split string with comma or space etc. based on requirement in jQuery.
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.
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.
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.
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With