[英]javascript get selected text not value
是否有可能获取所选文本的select
不是它的价值呢?
<select id="animals">
<option value="mammals">Elephant</option>
<option value="reptile">Snakes</option>
<option value="mammals">Bear</option>
<option value="birds">Ostrich</option>
</select>
我想知道正在选择的动物类型。
谢谢你的帮助。
function getSelectedText(elementId) {
var elt = document.getElementById(elementId);
if (elt.selectedIndex == -1)
return null;
return elt.options[elt.selectedIndex].text;
}
var text = getSelectedText('animals');
使用
Document.querySelector()
,返回文档中与指定选择器组匹配的第一个元素。
console.log(document.querySelector('#animals option:checked').textContent);
<script src="http://gh-canon.github.io/stack-snippet-console/console.min.js"></script> <select id="animals"> <option value="mammals">Elephant</option> <option value="reptile">Snakes</option> <option value="mammals">Bear</option> <option value="birds">Ostrich</option> </select>
jQuery:
$("#selection option:selected").text();
使用纯 Javascript:
this.options[this.selectedIndex].innerText
试试这个
它可以通过使用 javascript selectedIndex 和 text 方法来完成。
<!DOCTYPE html> <html> <body> <p>Choose an option in the drop-down list and display that option.</p> <form> <select id="mySelect" onchange="myFunction()"> <option value="mammals">Elephant</option> <option value="reptile">Snakes</option> <option value="mammals">Bear</option> <option value="birds">Ostrich</option> </select> </form> <p id="demo"></p> <script> function myFunction() { var x = document.getElementById("mySelect"); var i = x.selectedIndex; document.getElementById("demo").innerHTML = x.options[i].text; } </script> </body> </html>
我有一个类似的问题,我想将选定的文本(不是值)输出到 Textarea 框中。 我是这样解决的:
<label>Objectives :</label>
<select name="objectives" class="objectives" onchange="getObjectives(this);">
<option selected="selected">--Select Objectives--</option>
<option selected="selected">--One--</option>
<option selected="selected">--Two--</option>
</select>
<textarea rows="4" cols="30" id="objid"></textarea>
<script>
function getObjectives(sel) {
// Select option returns text instead of value of option
document.getElementById ("animals").value = sel.options[sel.selectedIndex].text;
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.