检索所选的< option>的文本在< select>元件
问题描述:
在以下内容中:
<select id="test">
<option value="1">Test One</option>
<option value="2">Test Two</option>
</select>
如何获取所选选项的文本(即Test One或Test Two )使用JavaScript
How can I get the text of the selected option (i.e. "Test One" or "Test Two") using JavaScript
document.getElementsById('test')。selectedValue
返回1或2,什么属性返回
document.getElementsById('test').selectedValue
returns 1 or 2, what property returns the text of the selected option?
答
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('test');