1

Possible Duplicate:
Assign click handlers in for loop

I'm a bit naive in javascript. I have this javascript code which is supposed to run on button click. Buttons are generated dynamically in a loop. What I was expecting was to receive different variable on each button click . But what I receive is always the last variable in array. See the code below. Do anyone see something obviouly wrong here ?

<!doctype html>
<html> 
<head>      
<script  type="text/javascript"> 

var myCars=["Saab","Volvo","BMW"]; 

    function loadCars() {
var carList = document.getElementById('mydiv');

for(var i=0;i < myCars.length ; i++ ){

//Append button
        var el = document.createElement("button");
        var car = myCars[i];
        el.name = "view_car";
        el.id = "view_car";
        el.value = "View car";
        el.type = "button";
        el.title = "View car "+i;
        el.innerHTML = "View car "+car;
        el.onclick = function() { 
            showMe(car,i);
        };

    carList.appendChild(el);
}

}

function showMe(carName,index){

    alert("Selected car="+carName +" , index="+index);
}

    </script>

</head>

<body  onload="loadCars()">

Cars will be loaded here 
<div  id="mydiv" class="carlist"></div>

</body>
</html>

Button click output

Community
  • 1
  • 1
Tushar
  • 1,607
  • 1
  • 16
  • 27

1 Answers1

3

There's nothing obvious wrong. However, you use car and i inside of your onclick function. Both depend on the outer car and i and are manipulated. You have to break this reference by using a closure:

    el.onclick = (function(carname,index){
        return function() { 
            showMe(carname,index);
        };
    })(car,i);
Zeta
  • 103,620
  • 13
  • 194
  • 236