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)
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.
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.
isChecked()) alert('this option is selected'); else alert('this is not'); });
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.
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
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With