查找这 在被选择 (不JQuery的)(Finding which

2019-08-06 21:55发布

我有以下要素:

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

我想找到选择的选项:

下面给我只有默认:

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

(我知道如何用jQuery做到这一点,但我不能使用jQuery或其他任何类似的库)

Answer 1:

在普通的JavaScript:

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

JsBin例如: http://jsbin.com/ogunet/1/edit (打开你的JS控制台)



Answer 2:

使用:检查选择。 这适用于复选框,单选,并选择

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

为节点

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

该值



Answer 3:

这将返回所选的选项的值和文本两种..希望这会为ü工作..

干杯

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

 // get option selected
    var option = elt.options[elt.selectedIndex].value;
    var optionText = elt.options[elt.selectedIndex].text;


Answer 4:

抓住<select> DOM使用元件getElementById()并采取其参数selectedIndex

var select = document.getElementById( 'color' ),
    selIndex = select.selectedIndex;,
    selElement = select.getElementsByTagName( 'option' )[ selIndex ];


文章来源: Finding which