2016-06-14 40 views
0

我需要使用Javascript訪問從下拉列表中選擇的值。但是,每次我選擇「列表項」作爲答案時,都會收到「空」。使用Javascript獲取在下拉列表中選擇的值(顯示爲空)

我的HTML頁面:

<select class="mySelect"> 
    <option value="st1" selected="selected">Create new Stream</option> 
    <option value="st1">Stream 1</option> 
    <option value="st2">Stream 2</option> 
    <option value="st3">Stream 3</option> 
    <option value="st4">Stream 4</option> 
</select> 

<input type="button" value="show attributes" class="panel-button-attr" onclick="choice()"> 

當點擊上面的按鈕,所選值應提醒用戶。所以在我的Javascript功能:

function choice() { 

    var choice=document.getElementById("mySelect"); 
    alert(choice); 
    var strUser = choice.options[choice.selectedIndex].text; 
    alert(strUser.toString()); 

} 

在這裏,我試圖使用第一個警報來檢查是否任何選定的列表項被正確識別。但是,在這一點上,它顯示爲空,並且strUsr行根本不運行。

我知道這實際上是一項微不足道的任務,但我很難發現這種不一致。

+0

如果* *的getElementById返回空這意味着它沒有找到的元素。 – RobG

+2

您試圖訪問ID爲「mySelect」的元素,但是您已將「mySelect」作爲類而不是HTML中的ID。 – Guillaume

+0

@ SpeedyNinja-no,簡單的編碼錯誤。 – RobG

回答

1

您必須指定選擇元素的id

<select class="mySelect" id="mySelect"> 
2

請改變你的HTML元素的屬性。

你已經提到'mySelect'是類,在JS中,你使用ID引用來調用它。

0

遵循代碼:

你需要給ID到下拉,因爲你試圖獲得通過的ID,這樣的數據...

<select id="mySelect" class="mySelect"> 
    <option value="st1" selected="selected">Create new Stream</option> 
    <option value="st1">Stream 1</option> 
    <option value="st2">Stream 2</option> 
    <option value="st3">Stream 3</option> 
    <option value="st4">Stream 4</option> 
</select> 

我希望這將解決您的問題....

謝謝...

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

的每次更改中調用函數選項()可以詳細說明您的答案,並添加關於您提供的解決方案的更多描述。 – abarisone

0

plunker:https://plnkr.co/edit/Q7yyVvUTaLYvPaDW5j7G?p=preview

<select id="mySelect" class="mySelect" > 
     <option value="st1" selected="selected">Create new Stream</option> 
     <option value="st1">Stream 1</option> 
     <option value="st2">Stream 2</option> 
     <option value="st3">Stream 3</option> 
     <option value="st4">Stream 4</option> 
    </select> 


function choice() { 

    var choice=document.getElementById("mySelect"); 
    alert(choice.value); // get value 
    var strUser = choice.options[choice.selectedIndex].text; 
    alert(strUser.toString()); 
} 
0

你沒有ID在你的HTML,所以我儘量按類名..

function choice() { 
    var choice=document.getElementsByClassName("mySelect"); 
    var strUser = choice[0].options[choice[0].selectedIndex].text; 
    alert(strUser.toString());    
} 
相關問題