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.
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(',');
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.
Look at map()
..
$('#lbID option').map(function() {
return $(this).val();
}).get().join(',');
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