Idiomatic jQuery to get all options in a listbox into comma-separated string?
Solution 1
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(',');
Solution 2
Look at map()
..
$('#lbID option').map(function() {
return $(this).val();
}).get().join(',');
Solution 3
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.
Solution 4
This is the jQuery equivalent to your code. There are more elegant solutions, though.
var values = [];
$(lb).children('option').each(function () {
values.push($(this).text());
});
$(txtfield).val(values.join(','));
Solution 5
Could do it like this but I'm not sure what you're trying to achieve?
$('option', $(lb)).each(function() { arr.push($(this).text()) });
Comments
-
Cade Roux over 1 year
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. -
Nick Craver over 13 yearsIn these cases it's far better to use
jQuery.map()
which is much less wasteful/faster, you can test it here: jsperf.com/map-vs-jquery-map -
El Ronnoco over 13 yearsSpent 10 mins getting that working and there another three similar answers already here!
-
Cade Roux over 13 yearsThanks all for the very thorough investigative work. I shall weigh keeping an optimized version of the loop code (which is better than what I was refactoring in the first place) vs. something which might be more succint or maintainable.