2016-07-07 98 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