Summary: I have passed the name of the id select tag into an Array. I want to dynamically assign each Select Item to display the Index of the selected item upon change. This is sent to the output div. Only the third select item is dynamically being triggered. Why?
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
var NameOfSelect=new Array("a","b","c");
for (i=0;i<NameOfSelect.length;i++){
var sel=NameOfSelect[i];
$("#"+NameOfSelect[i]).change(function () {
var str = "";
$("#"+sel+" option:selected").each(function () {
str += $(this).index() + " "+$("#"+sel).attr("id");
});
$("#output").text(str);
})
.trigger('change');
}
</script>
The HTML
<select id="a" >
<option value="0a" >0a</option>
<option value="1a" >1a</option>
<option value="2a" >2a</option>
</select>
<select id="b" >
<option value="0b" >0b</option>
<option value="1b" >1b</option>
<option value="2b" >2b</option>
</select>
<select id="c" >
<option value="0c" >0c</option>
<option value="1c" >1c</option>
<option value="2c" >2c</option>
</select>
<div id=output></div>
The output shows that only “C” is being triggered on change.
Why are “a” and “b” not being similarly dynamically assigned?
This occurs because the variable
cgets reassigned with every iteration. At the end of the for-loop, all elements will have a proper event handler, but they will refer to the samecvariable inside their function body. This variable will be holding the last value ofc, being"c".One solution would be to cache the value of
cin a closure for every function handler you assign, but in this case it’s much better to simply usethisinside the handler to refer to theselectelement that was targeted by thechangeevent.Also, unless you’re using
selects with multiple selections, there should only be oneoption:selectedfor eachselectelement. Therefore, you could just usefindand work with the first (and only) selectedoption.