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:01

If you use jQuery then you can write the following code:

$("#selectId option:selected").html();
查看更多
倾城一夜雪
3楼-- · 2019-01-02 21:04

Similar to @artur just without jQuery, with plain javascript:

// Using @Sean-bright's "elt" variable

var selection=elt.options[elt.selectedIndex].innerHTML;
查看更多
琉璃瓶的回忆
4楼-- · 2019-01-02 21:06

You can use selectedIndex to retrieve the current selected option:

el = document.getElementById('elemId')
selectedText = el.options[el.selectedIndex].text
查看更多
浮光初槿花落
5楼-- · 2019-01-02 21:07
document.getElementById('test').options[document.getElementById('test').selectedIndex].text;
查看更多
临风纵饮
6楼-- · 2019-01-02 21:07

If you found this thread and wanted to know how to get the selected option text via event here is sample code:

alert(event.target.options[event.target.selectedIndex].text);
查看更多
千与千寻千般痛.
7楼-- · 2019-01-02 21:14
function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

    if (elt.selectedIndex == -1)
        return null;

    return elt.options[elt.selectedIndex].text;
}

var text = getSelectedText('test');
查看更多
登录 后发表回答