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!
     }
}
1

2 Answers 2

24

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);
       }
     }
   }
Sign up to request clarification or add additional context in comments.

1 Comment

Unfortunately, doesn't work for very large datasets.
17

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.