Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Idiomatic jQuery to get all options in a listbox into comma-separated string?

Where lb is a listbox, txtfield is a textbox, this code takes all the values of the options, puts them in an array and makes it into a comma-separated list:

var arr = [];
for (var i = 0; i < lb.length; i++) {
    arr[i] = lb.options[i].value;
}
txtfield.value = arr.join(',');

lb.options.toString() obviously doesn't work because it's an array of options (value and text). I haven't found anything more succint than this.

What's the jQuery way to do this? I tried messing around with $(lb).each(), but can't seem to get it to work in the same way.

like image 431
Cade Roux Avatar asked Nov 16 '10 22:11

Cade Roux


3 Answers

txtfield.value = $(lb.options).map(function() { 
                                       return this.value; 
                                   }).get().join(',');

This uses .map() to create a jQuery object by returning the value of each option, then uses .get() to extract the Array from the object.


EDIT: As @Nick Craver noted in the comment below, if you need to get optimal performance (with jQuery), it makes more sense to use the $.map() variation since you already have a collection. See his answer for details.


EDIT: To get better performance, do your for loop, but cache the references to the properties. It makes a difference.

var arr = [], opts = lb.options, len = opts.length;
for (var i = 0; i < len; i++) {
    arr[i] = opts[i].value;
}
txtfield.value = arr.join(',');
like image 93
user113716 Avatar answered Sep 24 '22 01:09

user113716


The jQuery version is .map() like this:

var arr = $(lb).find("option").map(function() { return this.value; }).get();
txtfield.value = arr.join(',');

Or a bit faster with $.map() like this:

var arr = $.map(lb.options, function(o) { return o.value; });
txtfield.value = arr.join(',');

However, both are significantly less efficient than a for loop, go with the plain JavaScript version you already have.

like image 33
Nick Craver Avatar answered Sep 25 '22 01:09

Nick Craver


Look at map()..

$('#lbID option').map(function() {
  return $(this).val();
}).get().join(',');
like image 6
Quintin Robinson Avatar answered Sep 21 '22 01:09

Quintin Robinson