That's because the handlers you bind to change
do not run immediately, but later. In the meantime, your for
loop has run its course and slottime
has been rebound to its final value (the last <select>
element you created). All the handlers will only see that value.
You can introduce a closure in order for the right elements to be accessible to the handlers:
document.getElementById("slots").appendChild(slotlist);
(function(slottime) {
slottime.addEventListener("change", function() {
alert(slottime.id);
});
})(slottime);
As Teemu righfully says in the comments, the simplest solution is to take advantage of the fact that this
is bound to the target element inside the handler:
slottime.addEventListener("change", function() {
alert(this.id);
});