我的页面中有两个选择标记。其中每个都有几个选项。现在我只想访问第二个选择框,但由于我使用了getElementByTagName(“options”),所以它只获取第一个选项标签。我无法访问第二个选项标签。
我的代码在这里:
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 :(得分:1)
您需要在选择而不是整个文档上按标记名称获取元素
function myFunction()
{
var select = document.getElementById("mySelect_two");
var x = select.selectedIndex;
alert(select.getElementsByTagName("option")[x].value);
}
答案 1 :(得分: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;
答案 2 :(得分: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>