Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting selected options with querySelectorAll

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?

like image 574
GOTO 0 Avatar asked Mar 23 '13 12:03

GOTO 0


People also ask

What will querySelectorAll return?

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

Why querySelectorAll not working?

Originally Answered: Why is my querySelectorAll() method not working ? The reason is that you try to access DOM elements before they are part of the DOM. There is no reason to use the querySelector at all unless you have a table already you want to modify.

How do you use queryselectorall in JavaScript?

The JavaScript querySelectorAll method is used to select elements in the document using CSS selectors and returns all the matching elements as a list. The method returns a static NodeList (an array-like object) that contains a list of all elements that match the specified selectors or group of selectors.

What does queryselectorall return?

Definition and Usage. The querySelectorAll() method returns all elements in the document that matches a specified CSS selector(s), as a static NodeList object.

How to get the value of the selected option element?

We can get the selected option element from the select element with the value property, which has the value of the value attribute of the selected option element. We can also get all the options with the options property. selectedIndex gets the index of the selected option element.

How to get the value of selectedchoice in a select option?

const select = document.querySelector ("select"); const selectedChoice = select.value; console.log (selectedChoice) to get the select element with document.querySelector . Then we get the value of the value attribute of the select option element with the value property. And then we should see that selectedChoice is 2.


1 Answers

document.querySelectorAll('option:checked')

Works even on IE9 ;)

like image 190
a better oliver Avatar answered Oct 08 '22 01:10

a better oliver