Here is what I have done:
<html><head><script type="text/javascript">
function loaded(){
var selectElems=document.getElementsByName("select");
for(i=0;i<selectElems.length;i++){
var elem=selectElems[i];
elem.onchange=function(){
alert(elem.selectedIndex);
}
}
} </script></head>
<body onload="loaded()">
<select name="select">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option> </select>
<select name="select">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option></select>
<select name="select">
<option>0</option>
<option>1</option>
<option>2</option>
<option>3</option>
<option>4</option></select>
</body></html>
I need to get selected index of element with JavaScript. But I had a problem with that.
Here is my code: http://jsfiddle.net/aRMpt/139/
The problem is that your
elemalways points to the lastselectelement. The simplest solution is to usethisin the handler instead of the elem variable http://jsfiddle.net/mendesjuan/aRMpt/140/This doesn’t really tell you what your problem is though. It’s a workaround (though a good one). The reason your code doesn’t work is because your closure function
onchangeuses the sameelemfrom the closure. By the time youronchangeis called,elempoints to the lastselectelement. A way to avoid this is to introduce another closure that freezes the elem for your onchange handler http://jsfiddle.net/mendesjuan/aRMpt/142/Here’s another example that may help you understand how the above example works.
This freezing of variables could also be accomplished by using Function.bind, but this only works in newer browsers; however, the above link shows you how to make it work for browsers that don’t support it. http://jsfiddle.net/mendesjuan/aRMpt/143/