I am trying to create a list dynamically via javascript by clicking a button. This list is created properly. Each item of this list has an onclick function with a different argument. So, by clicking on each item, an other word("Saab" or "Volvo" or "BMW") is printed on the screen. The problem is that by clicking on every item of the list, only the last word("BMW") is printed.
This is my html and javascript code.
function myfunction1() {
var i;
var cars = ["Saab", "Volvo", "BMW"];
for (i = 0; i < cars.length; i = i + 1) {
var y = cars[i];
var mycar = cars[i];
var li = document.createElement('li');
var a = document.createElement('a');
a.innerHTML = y;
a.onclick = function() {
showcar(mycar);
}
li.appendChild(a);
document.getElementById("allcars").appendChild(li);
}
}
function showcar(car) {
document.getElementById("demo").innerHTML = car;
}
<button onclick="myfunction1()">Perla</button>
<ul>
<p id="allcars"></p>
</ul>
<p id="demo"></p>
If I click on Saab or Volvo or BMW only BMW will be printed on the screen. What I want is: when I click on Saab item of the list, "Saab" is printed. When I click on Volvo item, "Volvo" is printed. When I click on "BMW" item, "BMW" is printed.