Creating a comma delimited string from a selected item in jQuery

This is what happens. I have a select element for which I need to get a comma-delimited string from all of its options, regardless of whether it is selected or not.

How can I do the following in jQuery / javascript:

    <select id="currentTags" multiple>
        <option>Nature</option>
        <option>Cats</option>
        <option>Space</option>
    </select>

and turn it into this:

    "Nature, Cats, Space"

I tried to find ways to do this and could not ... I am still learning javascript and my limited knowledge stops me on my tracks.

Any help would be appreciated, even if it just helps me in the right direction. Thank you for your time.

+3
source share
5 answers

Using jQuery:

var result = $('#currentTags option').map(function(i, opt) {
  return $(opt).text();
}).toArray().join(', ');

In simple JavaScript, you can do something like this:

// Convert pseudo-arrays to real arrays
var __slice = Array.prototype.slice;

// Get select options as real array
var opts = __slice.call(document.querySelectorAll('#currentTags option'));

// Map the text of each option
var result = opts.map(function(x) {
  return x.textContent;
}).join(', ');

console.log(result); //=> "Nature, Cats, Space"

, API (, jQuery), , .

DOM , , . MDN, querySelectorAll, children, textContent .

: IE9 + .

+12

:

// Initialize your string
var output_string = "";

// For each 'option' tag, append its value to the string with the comma
$('#currentTags option').each(function() {
    output_string = output_string+this.text;
});

// Removing the last ', ' which were added during the loop
output_string = output_string.substr(0, output_string.length-2);

, :)

+1

javascript (POJS) , , , , .

var options = document.getElementById('currentTags').options;
var values = [];

for (var i=0, iLen=options.length; i<iLen; i++) {
  values.push(options[i].text);
}

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

You can write that in a much more concise form, but performance may suffer and, depending on the features used, may fail in some browsers. The above award guarantees clarity and ease of maintenance of the code, performance will be at least as fast as any alternative.

+1
source

How about just:

var tags = [];
$('#currentTags option').each(function() {
    tags.push($(this).val());
});

console.log(tags.join(', ')); // 'Nature, Cats, Space'

http://jsfiddle.net/wN2Dk/

+1
source

Here is a simple jQuery example:

var arr = []; // create array

$('#currentTags').children().each(function() {
    arr.push($(this).text()); // add option text to array
});

alert(arr.join(', ')); // Nature, Cats, Space

If you need an option value, switch text()to val();)

+1
source

All Articles