Quantcast
Viewing latest article 2
Browse Latest Browse All 10

JavaScript retrieving text of selected option in select element

Problem And Question

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?

Thanks for help!

Best Solution And Answer

function getSelectedText(elementId) {
    var elt = document.getElementById(elementId);

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

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

var text = getSelectedText('test');

Viewing latest article 2
Browse Latest Browse All 10

Trending Articles