DropDown List SelectedIndex is not working with getElementById in javascript

你离开我真会死。 提交于 2019-12-11 17:52:10

问题


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>

回答1:


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>

I hope you aren't being confused by having options values 1, 2 and 3 correlate to selectedIndexes 0, 1 and 2.




回答2:


Because you call the function onChange event i.e not in the past. Try to trigger the function without onchange event and the property is selected in the past

        <select name='batches' id='batches' onchange='someFunc();'>
<option value = "1">1</option>
<option value = "2">2</option>
<option value = "3">3</option>
</select>
<a href="javascript:someFunc()">Test</a>

<script>
function someFunc(){
   //var myindex  = dropdown.selectedIndex;// This prints correctly
   alert("Index : "+document.getElementById("batches").selectedIndex);// This is always 0 no metter what selects        
}
</script>

it will work. Just copy and paste this code into your text editor and test it



来源:https://stackoverflow.com/questions/11856000/dropdown-list-selectedindex-is-not-working-with-getelementbyid-in-javascript

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!