2008-08-08 84 views
61

這會獲取我的下拉菜單中所選內容的值。從下拉框中獲取文本

document.getElementById('newSkill').value 

但是,我不能找出下拉菜單中當前顯示的文本的屬性。我試過「文字」,然後看着W3Schools,但沒有答案,這裏有人知道嗎?

對於那些不確定的,這裏是一個下拉框的HTML。

<select name="newSkill" id="newSkill"> 
    <option value="1">A skill</option> 
    <option value="2">Another skill</option> 
    <option value="3">Yet another skill</option> 
</select> 

回答

111

根據您的示例HTML代碼,這裏有一個方法來獲得當前選定的選項的顯示文本:

var skillsSelect = document.getElementById("newSkill"); 
var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text; 
+3

對於那些遲到的人來說,有幾個建議,但沒有人注意到他們說.value他們應該說什麼.text,這是一個令人困惑的日子,對我們來說都是如此。 – Teifion 2008-09-19 10:59:14

1

這是否得到正確答案?

document.getElementById("newSkill").innerHTML 
+5

這將返回該選項的整個HTML代碼..像 ` <選項值= 「1」>甲技能 <選項值=」 2「>另一種技能 ` – 2011-11-29 11:36:37

7
document.getElementById('newSkill').options[document.getElementById('newSkill').selectedIndex].value 

應工作

+2

OP要的是.text屬性,而不是。價值 – ninjaPixel 2013-10-29 16:32:42

8

這應該返回選定值

var vSkill = document.getElementById('newSkill'); 

var vSkillText = vSkill.options[vSkill.selectedIndex].innerHTML; 

alert(vSkillText); 

道具的文本值:@Tanerax讀取的問題,知道什麼被問和回答之前它其他人發現它。

編輯:DownModed,因爲我實際上完全閱讀一個問題,並回答它,它是悲傷的世界。

4

這工作我嘗試了我自己,我想我張貼在這裏萬一有人需要它...

document.getElementById("newSkill").options[document.getElementById('newSkill').selectedIndex].text; 
0
var ele = document.getElementById('newSkill') 
    ele.onchange = function(){ 
      var length = ele.children.length 
      for(var i=0; i<length;i++){ 
       if(ele.children[i].selected){alert(ele.children[i].text)};    
      } 
    } 
2

附加一個改變事件的選擇得到每個選擇的選項的文本,在div寫到他們。

您可以使用jQuery它很有面子和成功的和易於使用的

<select name="sweets" multiple="multiple"> 
    <option>Chocolate</option> 
    <option>Candy</option> 
    <option>Taffy</option> 
    <option selected="selected">Caramel</option> 
    <option>Fudge</option> 
    <option>Cookie</option> 
</select> 
<div></div> 


$("select").change(function() { 
    var str = ""; 

    $("select option:selected").each(function() { 
    str += $(this).text() + " "; 
    }); 

    $("div").text(str); 
}).change(); 
0
var selectoption = document.getElementById("dropdown"); 
var optionText = selectoption.options[selectoption.selectedIndex].text; 
+0

如何解釋一些文字來解釋發生了什麼? – nottinhill 2016-02-11 02:33:21

0

請嘗試以下,這是最簡單的方法和它完美的作品

var newSkill_Text = document.getElementById("newSkill")[document.getElementById("newSkill").selectedIndex]; 
4

只要你可以使用Jquery代替Javascript

$("#yourdropdownid option:selected").text(); 

試試這個。

0
function getValue(obj) 
{ 
    // it will return the selected text 
    // obj variable will contain the object of check box 
    var text = obj.options[obj.selectedIndex].innerHTML ; 

} 

HTML摘錄

<asp:DropDownList ID="ddl" runat="server" CssClass="ComboXXX" 
    onchange="getValue(this)"> 
</asp:DropDownList>