下拉列表SelectedIndex不适用于javascript中的getElementById [英] DropDown List SelectedIndex is not working with getElementById in javascript
问题描述
我有一个名为批次的下拉列表.
如果我选择了第二个选项,则OnChange函数中的dropdown.selectedIndex始终显示选定的索引.
但是document.getElementById("batches").selectedIndex始终显示第一个索引.
为什么呢?
实际上,我想在另一个函数中读取正确的批次的selectedIndex,这就是为什么我需要一种方法来以两种方式获取正确的所选索引.
I have a DropDown list named as batches.
If I selected 2nd option,dropdown.selectedIndex inside the OnChange function always shows the selected index.
But document.getElementById("batches").selectedIndex always shows the 1st index.
Why is this?
Actually I want read the correct selectedIndex of batches in another function that's why I need a way to get the correct selected index in both ways.
function OnChange(dropdown){
var myindex = dropdown.selectedIndex;// This prints correctly
alert("Index : "+document.getElementById("batches").selectedIndex);// This is always 0 no metter what selects
}
<select name='batches' id='batches' onchange='OnChange(this);'>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
推荐答案
我不知道您要在哪种浏览器中进行测试,但是以下内容在我测试过的所有浏览器中始终显示为真:
I don't know what browser you are testing in, but the following always shows true in all browsers I tested in:
<select id="batches" onchange="
alert(this.selectedIndex == document.getElementById('batches').selectedIndex);
">
<option value = "1">1
<option value = "2">2
<option value = "3">3
</select>
<!-- and to confirm... -->
<button onclick="
alert(document.getElementById('batches').selectedIndex);
">Show selected index</button>
我希望您不要因选项值1、2和3与selectedIndexes 0、1和2相关而感到困惑.
I hope you aren't being confused by having options values 1, 2 and 3 correlate to selectedIndexes 0, 1 and 2.
这篇关于下拉列表SelectedIndex不适用于javascript中的getElementById的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!