Finding which

2020-07-23 05:47发布

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)

5条回答
冷血范
2楼-- · 2020-07-23 06:11

Grab the <select> DOM element using getElementById() and take its parameter selectedIndex:

var select = document.getElementById( 'color' ),
    selIndex = select.selectedIndex;,
    selElement = select.getElementsByTagName( 'option' )[ selIndex ];
查看更多
闹够了就滚
3楼-- · 2020-07-23 06:13

You can do this with querySelectorAll not querySelector

document.querySelectorAll('option:checked')[0].innerText

or

document.querySelectorAll('option:checked')[0].value
查看更多
Bombasti
4楼-- · 2020-07-23 06:32

This will return selected option value and text both.. Hope this will work for u ..

Cheers

var elt = document.getElementById('color');

 // get option selected
    var option = elt.options[elt.selectedIndex].value;
    var optionText = elt.options[elt.selectedIndex].text;
查看更多
三岁会撩人
5楼-- · 2020-07-23 06:33

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

查看更多
何必那么认真
6楼-- · 2020-07-23 06:36

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)

查看更多
登录 后发表回答