获取多选下拉列表的selectedIndex

时间:2019-06-17 11:45:13

标签: javascript html

我有一个HTML选择下拉列表,其中提供了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

5 个答案:

答案 0 :(得分:2)

一个选项:

// 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's sensible use of 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>

参考文献:

答案 1 :(得分:1)

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>

答案 2 :(得分:0)

尝试这样。

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

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>

答案 3 :(得分:0)

获取所有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>

答案 4 :(得分:0)

SELECT 
MRPRJPROJTRANSPOSTING.VOUCHER,
[Factuuromschrijving(en)] = STUFF(
    (SELECT ',' + LEDGERTRANS.TXT 
        FROM LEDGERTRANS
        WHERE LEDGERTRANS.VOUCHER = MRPRJPROJTRANSPOSTING.VOUCHER 
AND LEDGERTRANS.DATAAREAID = MRPRJPROJTRANSPOSTING.DATAAREAID FOR 
XML PATH (''))
        , 1, 1, '' )
FROM MRPRJPROJTRANSPOSTING

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

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);
})