Getting selected options with querySelectorAll

拈花ヽ惹草 提交于 2019-12-21 06:55:05

问题


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?


回答1:


document.querySelectorAll('option:checked')

Works even on IE9 ;)




回答2:


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


来源:https://stackoverflow.com/questions/15586577/getting-selected-options-with-queryselectorall

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!