document.querySelectorAll('option:checked')
Works even on IE9 ;)
Question
I wonder if it's possible in Javascript to get the currently selected options in a <select multiple>
field using the Selctors API rather than a "stupid" iteration over all options.
select.querySelectorAll('option[selected="selected"]')
only returns the options that were marked as preselected in the original HTML, which is not what I'm looking for. Any ideas?
Solution
document.querySelectorAll('option:checked')
Works even on IE9 ;)
OTHER TIPS
I was also experienced your issue, I have a feeling it's to do with JavaScript not recognising changes in the DOM.
Here is a solution:
document.getElementById('test').onclick = function () {
var select = document.getElementById('select');
var options = getSelectedOptions(select);
console.log(options);
};
function getSelectedOptions(select) {
var result = [];
var options = select.getElementsByTagName('option');
for (var i = 0; i < options.length; i++) {
if (options[i].selected)
result.push(options[i]);
};
return result;
}
As described in
https://www.w3schools.com/jsref/prop_select_selectedindex.asp
you can get the currently selected index with selectObject.selectedIndex
It also changes in a change
eventListener.
For example:
id_selected = document.querySelector('#sel').selectedIndex;
console.log(document.querySelector('#sel')[id_selected]);