繁体   English   中英

获取多选下拉列表的selectedIndex

[英]Get selectedIndex of a multiple select dropdown

我有一个HTML select下拉列表,其中提供了multiple

<select multiple id="mySelect">
  <option>Apple</option>
  <option>Orange</option>
  <option>Pineapple</option>
  <option>Banana</option>
</select>

并分配一个点击处理程序,该处理程序返回当前点击的元素的索引:

document.getElementById("mySelect").onclick = function() {
  alert(this.selectedIndex);
}

当我仅选择其中一个元素时,它可以正常工作。 但是我想返回当前选择的所有索引。

当我单击Apple, Orange and Banana ,我想要的是[0,1,3]这样的返回值,但它不起作用。

工作示例: JSfiddle

一种选择:

 // named function for reuse, not using Arrow syntax in // order that we can retain, and use the 'this' within // the function: const retrieveSelectedIndices = function() { // here we use the spread operator to // expand the iterable this.options collection, // allowing us to call Array.prototype.map() // (Array.from(this.options) would be more or less // identical: const selected = [...this.options].map( // we're not using 'this', so using Arrow // function expression; here we use a ternary // to return the index of the current <option> // if it is selected, or Boolean false if not: (opt, index) => opt.selected ? index : false // we then call Array.prototype.filter() on // the Array created by Array.prototype.map(), // and here we test that i - the index retrieved // previously - is not equal to false: ).filter(((i) => i !== false)); // we log the indices to the console(), but this is // where you could work with the indices, for logging // to an HTML <ul></ul> element, for example: console.log(selected); // and returning to the calling context, in the event // this function will be used in an alternative manner: return selected; } // using document.querySelector() to retrieve the first, // and only, element matching the supplied CSS selector: selectEl = document.querySelector('#mySelect'); // binding a function, the retrieveSelectedIndices() // function, as the 'input' event-handler for on // the <select id="mySelect"> element: selectEl.addEventListener('input', retrieveSelectedIndices); 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

请注意,上面的功能不保持所选元素/取消选中元素的顺序。

编辑为使用HTMLSelectElement.selectedOptions代替HTMLSelectElement.options ,在评论中进行讨论之前,我会忘记它的存在。 这反映了一种更新,而不是任何尝试获得Daryll明智使用HTMLSelectElement.selectedOptions

也就是说,上述代码可以轻松修改为以下代码:

 // named function for reuse, not using Arrow syntax in // order that we can retain, and use the 'this' within // the function: const retrieveSelectedIndices = function() { // here we use the spread operator to // expand the iterable this.selectedOptions collection, // a HTMLCollection of the currently-selected <option> // elements, allowing us to call Array.prototype.map() // (Array.from(this.selectedOptions) would be more or less // identical: const selected = [...this.selectedOptions].map( // we're not using 'this', so using Arrow // function expression; here we use a ternary // to return the index of the current <option> // if it is selected, or Boolean false if not: (opt) => opt.index ) // we log the indices to the console(), but this is // where you could work with the indices, for logging // to an HTML <ul></ul> element, for example: console.log(selected); // and returning to the calling context, in the event // this function will be used in an alternative manner: return selected; } // using document.querySelector() to retrieve the first, // and only, element matching the supplied CSS selector: selectEl = document.querySelector('#mySelect'); // binding a function, the retrieveSelectedIndices() // function, as the 'input' event-handler for on // the <select id="mySelect"> element: selectEl.addEventListener('input', retrieveSelectedIndices); 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

参考文献:

没有针对该selectedOptions的浏览器API,但不支持IE。

 document.getElementById("mySelect").onclick = function() { console.log(Array.from(this.selectedOptions).map(option => option.index)) } 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

尝试这样。

我已经遍历了选项,并检查了选定的选项并将其推送。 最后,我加入了阵列并进行了打印。

 var selectEl = document.querySelector('#mySelect'); var options = document.querySelectorAll('#mySelect option'); selectEl.addEventListener('click', function() { var arr=[] options.forEach(function(option, index) { if(option.selected) { arr.push(index); } }) console.log(arr.join(",")); }) 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

获取所有options 将更改事件添加到您的select ,获取选定的选项,对其进行迭代以查找单个选定选项的索引。

 const options = document.querySelectorAll('#mySelect > option'); let indexes = []; document.querySelector('#mySelect').addEventListener('change', function() { indexes = []; const selectedOptions = this.selectedOptions; [...selectedOptions].forEach((option) => { const index = [...options].indexOf(option); indexes.push(index) ; }) console.log(indexes); }); 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

allTheOptions.forEach(function(items,i) {
    if (items.selected) {
      answer.push(i);
    }
  })
};

如果选择该项,则将索引推入数组。 就那么简单。

 let allTheOptions = document.querySelectorAll('#mySelect option'); let select = document.querySelector('#mySelect'); select.addEventListener('change', function() { let answer = []; allTheOptions.forEach(function(items,i) { if (items.selected) { answer.push(i); } }) console.log(answer); }) 
 <select multiple id="mySelect"> <option>Apple</option> <option>Orange</option> <option>Pineapple</option> <option>Banana</option> </select> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM