20

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!
     }
}
Mark Kennedy
  • 1,751
  • 6
  • 30
  • 53
  • 2
    See also https://stackoverflow.com/questions/2950152/iterate-through-select-options?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa – rogerdpack Apr 26 '18 at 04:42

2 Answers2

22

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);
       }
     }
   }
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
16

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...

dandavis
  • 16,370
  • 5
  • 40
  • 36