Retrieving the text of the selected

2019-01-02 20:32发布

In the following:

<select id="test">
    <option value="1">Test One</option>
    <option value="2">Test Two</option>
</select>

How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript

document.getElementsById('test').selectedValue returns 1 or 2, what property returns the text of the selected option?

12条回答
有味是清欢
2楼-- · 2019-01-02 21:20

The options property contains all the <options> - from there you can look at .text

document.getElementById('test').options[0].text == 'Text One'
查看更多
零度萤火
3楼-- · 2019-01-02 21:21

Use the select list object, to identify its own selected options index. From there - grab the inner HTML of that index. And now you have the text string of that option.

<select onchange="alert(this.options[this.selectedIndex].innerHTML);">
       <option value="">Select Actions</option>
       <option value="1">Print PDF</option>
       <option value="2">Send Message</option>
       <option value="3">Request Review</option>
       <option value="4">Other Possible Actions</option>
    </select>
查看更多
浪荡孟婆
4楼-- · 2019-01-02 21:21

Easy, simple way:

const select = document.getElementById('selectID');
const selectedOption = [...select.options].find(option => option.selected).text;
查看更多
萌妹纸的霸气范
5楼-- · 2019-01-02 21:24
selectElement.options[selectElement.selectedIndex].text;

References:

查看更多
与风俱净
6楼-- · 2019-01-02 21:24

this.options[this.selectedIndex].innerText

查看更多
裙下三千臣
7楼-- · 2019-01-02 21:27

Under HTML5 you are be able to do this:

document.getElementById('test').selectedOptions[0].text

MDN's documentation at https://developer.mozilla.org/en-US/docs/Web/API/HTMLSelectElement/selectedOptions indicates full cross-browser support (as of at least December 2017), including Chrome, Firefox, Edge and mobile browsers, but excluding Internet Explorer.

查看更多
登录 后发表回答