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

1
  • 1
    problem is javascript doesnt save the values car,i for each of the buttons which are generated dynamically Commented Aug 6, 2012 at 10:27

1 Answer 1

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);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.