Reputation: 324820
Every relevant "question that may already have [my] answer" uses jQuery, which I am not using.
So, is there any simple way to get the values of selected options in a <select multiple>
tag, or do I have to loop through all the options to see which ones are selected and manually build an array?
Side-question: Which browsers don't support selectElement.value
and instead require selectElement.options[selectElement.selectedIndex].value
?
Upvotes: 4
Views: 5425
Reputation: 25091
You could also simply track the selected options via the onchange
event in real-time and collect them whenever you want them. I admit it's still looping, but at least you're not doing it every time you need to retrieve the selected options, and it has the added bonus of being simple (come retrieval time, anyway...). Working fiddle: http://jsfiddle.net/cyg9Z/
var Test;
if (!Test) {
Test = {
};
}
(function () {
Test.trackSelected = function (e) {
var selector = document.getElementById('selector'),
selected = [],
i = 0;
for (i = 0; i < selector.children.length; i += 1) {
if (selector.children[i].selected) {
selected.push(selector.children[i].value)
}
}
selector.selMap = selected;
};
Test.addListeners = function () {
var selector = document.getElementById('selector'),
tester = document.getElementById('tester');
selector.onchange = Test.trackSelected;
tester.onclick = Test.testSelected;
};
Test.testSelected = function () {
var div = document.createElement('div');
div.innerText = document.getElementById('selector').selMap.join(', ');
document.body.appendChild(div);
};
Test.addListeners();
}());
Upvotes: 0
Reputation: 29569
If you end up wanting to loop through and grab the selected values you could use something like this:
function loopSelected()
{
var txtSelectedValuesObj = "";
var selectedArray = new Array();
var selObj = document.getElementById('selectID');
var i;
var count = 0;
for (i=0; i<selObj.options.length; i++) {
if (selObj.options[i].selected) {
selectedArray[count] = selObj.options[i].value;
count++;
}
}
txtSelectedValuesObj = selectedArray;
alert(txtSelectedValuesObj);
}
You can view an example HERE, adapted from this example.
.
Upvotes: 0
Reputation: 154968
You can use select.selectedOptions
. However, this returns an HTMLCollection
, so you still have to clean it to get a string array. http://jsfiddle.net/9gd9v/
<select multiple>
<option value="foo" selected>foo</option>
<option value="bar">bar</option>
<option value="baz" selected>baz</option>
</select>
and:
var select = document.querySelector("select");
var values = [].map.call(select.selectedOptions, function(option) {
return option.value;
});
Upvotes: 3