Getting selected options with querySelectorAll
Asked Answered
P

3

34

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?

Porshaport answered 23/3, 2013 at 12:6 Comment(1)
I think your only option is to iterate over all option elements and filter out the ones that are not selected.Eruptive
E
71

document.querySelectorAll('option:checked')

Works even on IE9 ;)

Embree answered 23/3, 2013 at 14:26 Comment(3)
Should work with 9.0, Browser compatibility at the bottomEmbree
If jQuery is an option then you could use the :selected SelectorEmbree
Thanks for sharing. The tramp here is that works with "checked" and not "selected"Lin
W
0

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]);
Wadsworth answered 7/1, 2022 at 12:34 Comment(1)
I think that last line may need to be console.log(document.querySelector('#sel').options[id_selected]);Erminna
D
-1

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:

jsFiddle

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;
}
Dewberry answered 23/3, 2013 at 12:10 Comment(1)
JS recognizes these changes to the DOM. The problem is that the selected DOM property is non-serializable. The selected attribute corresponds to the defaultSelected DOM property, so querying for the attribute as in [selected] will return elements that have defaultSelected DOM property set to true.Deangelo

© 2022 - 2024 — McMap. All rights reserved.