2016-07-07 99 views
0

我的頁面中有兩個選擇標籤。其中每個都有幾個選項。現在我只想訪問第二個選擇框,但由於我使用了getElementByTagName(「options」),所以它只提取第一個選項標記。我無法訪問第二個選項標記。與getElementByTagName相關的問題

我的代碼是在這裏:

function myFunction() { 
 
    var x = document.getElementById("mySelect_two").selectedIndex; 
 
    alert(document.getElementsByTagName("option")[x].value); 
 
}
<!DOCTYPE html> 
 
<html> 
 
    <body> 
 

 
    Select your favorite fruit: 
 
    <select id="mySelect_one"> 
 
    <option value="apple">Apple</option> 
 
    <option value="orange">Orange</option> 
 
    <option value="pineapple">Pineapple</option> 
 
    <option value="banana">Banana</option> 
 
    </select> 
 

 
    <select id="mySelect_two"> 
 
    <option value="India">India</option> 
 
    <option value="Nepal">Nepal</option> 
 
    <option value="Spain">Spain</option> 
 
    <option value="Mexico">Mexico</option> 
 
    </select> 
 

 
    <p>Click the button to return the value of the selected fruit.</p> 
 

 
    <button type="button" onclick="myFunction()">Try it</button> 
 

 
    </body> 
 
</html>

+0

所以選擇的選項選擇,而不是整個文檔。 – epascarello

+0

該怎麼做?其實在我的代碼我剛纔提到的getElementById(「mySelect_two」),但它仍然是從選擇ID爲「mySelect_one」獲取的選項 – Abhradip

+0

所以你已經選擇的元素來獲得指標,做同樣的事情得到的選項。 – epascarello

回答

1

你需要獲得通過標籤名稱的元素上的選擇,而不是整個文件下面的腳本

function myFunction() 
{ 
    var select = document.getElementById("mySelect_two"); 
    var x = select.selectedIndex; 
    alert(select.getElementsByTagName("option")[x].value); 
} 
+0

日Thnx gurvinder ,,,這是工作 – Abhradip

0

與選項

var sel = document.getElementById("mySelect_two"); 
var selectedIndex = sel.selectedIndex; 
var value = sel.options[selectedIndex].value; 

與的getElementsByTagName

var sel = document.getElementById("mySelect_two"); 
var selectedIndex = sel.selectedIndex; 
var value = sel.getElementsByTagName("option")[selectedIndex].value; 
0

用它來獲得選擇的選項值:

var e = document.getElementById("mySelect_two"); 
 
var str = e.options[e.selectedIndex].value; 
 
alert(str)
<select id="mySelect_two"> 
 
<option value="India">India</option> 
 
<option value="Nepal" selected>Nepal</option> 
 
<option value="Spain">Spain</option> 
 
<option value="Mexico">Mexico</option> 
 
</select>

+0

抱歉,這是不工作...你沒收到我的問題。我問它與多個相同的標籤名稱造成問題 – Abhradip