I'm surprised I can't find this code online!
How do I access ALL the selected indices of a select list? Not just the first one?
HTML:
<select name="trends[]" multiple="multiple" id="trends" size="35"></select>
js:
function moveSelectedTrends()
{
var selectedTrends = document.getElementById('trends');
for(var i=0; i < selectedTrends.length; i++)
{
alert(selectedTrends.options[selectedTrends.selectedIndex].value) //ONLY returns the first selected element!
}
}
one simple way to avoid loops is to QSA:
[].forEach.call( document.querySelectorAll('#trends :checked') , function(elm){
alert(elm.value);
})
the :checked selector is smart enough to work on < select > menus...
Use i
instead of selectedTrends.selectedIndex
and test if it is selected
.
function moveSelectedTrends() {
var trends = document.getElementById('trends'), trend, i;
for(i = 0; i < trends.length; i++) {
trend = trends[i];
if (trend.selected) {
alert(trend.value);
}
}
}
来源:https://stackoverflow.com/questions/21343216/javascript-loop-through-all-html-select-option