Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript loop through ALL HTML select <option>

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!
     }
}
like image 285
Mark Kennedy Avatar asked Jan 24 '14 21:01

Mark Kennedy


1 Answers

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);
       }
     }
   }
like image 160
Quentin Avatar answered Oct 25 '22 23:10

Quentin