首页 > 解决方案 > 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 处读取未定义的属性“未定义”。请问我该怎么做?怎么了 ?

标签: javascriptselect

解决方案


过滤选定的选项,然后获取其文本内容。为了做到这一点,将选项属性转换为数组,然后使用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>


推荐阅读