[英]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.