javascript - JavaScript selectedIndex 文本上的多项选择
问题描述
我使用 Symfony Twig 模板在我的输入中有一个标签列表:
<select id="choices-multiple-remove-button" class="form-control" name="choices-multiple-remove-button" placeholder="Compétences" multiple>
{% for skill in skills %}
<option value="{{skill.id}}">{{skill.label}}</option>
{% endfor %}
</select>
</div>
在 JS 中,我可以获取使用 "elements[i].value" 选择的所有值:
function hello() {
var elements = document.getElementById('choices-multiple-remove-button');
for(var i=0; i < elements.length; i++) {
console.log(elements[i].value);
console.log(elements[i].options[elements[i].selectedIndex].text);
// Throw Error //
}
}
document.getElementById("workingbutton").addEventListener("click", hello);
这里 :
console.log(elements[i].options[elements[i].selectedIndex].text);
无法在 HTMLButtonElement.hello 处读取未定义的属性“未定义”。请问我该怎么做?怎么了 ?
解决方案
过滤选定的选项,然后获取其文本内容。为了做到这一点,将选项属性转换为数组,然后使用Array#filter
方法过滤选定的选项,最后使用Array#map
从选定的选项中提取文本值到数组中。
var element = document.getElementById('choices-multiple-remove-button');
console.log([...element.options].filter(ele => ele.selected).map(ele => ele.text));
<select id="choices-multiple-remove-button" class="form-control" name="choices-multiple-remove-button" placeholder="Compétences" multiple>
<option value="1" selected>1</option>
<option value="2" selected>2</option>
</select>
推荐阅读
- java - 如何使用 tablayout 和 Fragments 管理 java 文件
- c# - 设置 MinWidth 时 ListBox 获得 Height 1px
- python - 如何使 tcp ip 服务器连接始终保持在线
- python - 如何抓取不是另一个 div 的子级的 HTML div?
- reactjs - 使用 Recoil 和 React 创建高效的 Master Details UI 的规范方法是什么
- object - 无法访问 Jenkins/Groovy 中 LinkedHashMap 中嵌套映射的键和值
- list - 为什么flutter中List类的map方法不再起作用了?
- git - 从 git PR 中删除文件夹
- python - 如何创建已通过原始 DF 过滤的新数据框
- pandas - 识别多个列中的任何一个具有特定值的索引?