Javascript循环遍历所有HTML选择<选项> [英] Javascript loop through ALL HTML select <option>

查看:83
本文介绍了Javascript循环遍历所有HTML选择<选项>的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶我在网上找不到这个代码!

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 = trend []multiple =multipleid =trendssize =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!
     }
}


推荐答案

一避免循环的简单方法是QSA:

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

这篇关于Javascript循环遍历所有HTML选择&lt;选项&gt;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆