Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding which <Option> is selected in <select> (without JQuery)

I have the following Element:

<select id="color" name="colorId" class="btn secondary">
    <option value="347366" selected="selected">Purple</option>
    <option value="56634">White</option>
</select>

And I want to find which option is selected:

The following give me only the default:

document.querySelector('#color option[selected="selected"]')

(I know how to do it with JQuery but, I can't use jQuery or any other similar library)

like image 865
Guy Korland Avatar asked Jan 15 '13 08:01

Guy Korland


People also ask

How can check select option selected or not in jQuery?

Answer: Use the jQuery :selected Selector You can use the jQuery :selected selector in combination with the val() method to find the selected option value in a select box or dropdown list.

How do I know which option is selected in dropdown?

The selectedIndex property returns the index of the currently selected element in the dropdown list. This index starts from 0 and returns -1 if no option is selected. The options property returns the collection of all the option elements in the <select> dropdown list.

How do you check if a option is selected or not?

isChecked()) alert('this option is selected'); else alert('this is not'); });

How do you select a particular option in a select element in Javascript?

Use the selectedIndex and value to get the index and value of the selected option. The HTMLOptionElement represents the <option> element. If the option is selected, the selected property is true. The selectedText and selectedValue properties return the text and value of the selected option.


2 Answers

Use the :checked selector. This applies to checkbox, radio, and select

document.querySelector('#color option:checked')

for the node

document.querySelector('#color option:checked').value

for the value

like image 183
Seifu Avatar answered Oct 10 '22 19:10

Seifu


In plain javascript:

var select = document.getElementById('color');
var currentOpt = select.options[select.selectedIndex]; 

JsBin example: http://jsbin.com/ogunet/1/edit (open your js console)

like image 38
Fabrizio Calderan Avatar answered Oct 10 '22 20:10

Fabrizio Calderan