Javascript loop through ALL HTML select <option>

烈酒焚心 提交于 2019-11-27 16:15:49

问题


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:


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




回答2:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!