'how to display the value of an array using innerHTML?
I have an array n i have a four buttons n I just want to display array values ,if i click on first button ,first value should be displayed ,click on second button ,second value should be displayed n so on using addEventListener event handler but there is a problem when i click it directly display last value?
var element = document.querySelectorAll('.box1');
var city = document.querySelector('#name');
for (var i = 0; i < element.length; i++) {
element[i].addEventListener('click', function () {
var i = 0;
var places = ['San diago,USA', 'chicago,USA', 'phoenix,USA', 'New york,USA'];
while (i <places.length) {
console.log(city.innerHTML = places[i]);
i++;
}
});
}
Solution 1:[1]
You were iterating over the list of buttons, then inside each handler were also iterating over the full list (using the same variable i). Each button only needs one handler, so you only need one loop.
I moved your "Cities" array outside the function, there's no reason to define it separately inside each handler.
const places = ['San diego,USA', 'chicago,USA', 'phoenix,USA', 'New york,USA'];
let element = document.querySelectorAll('.box1');
let city = document.querySelector('#name');
for (let i = 0; i < element.length; i++) {
element[i].addEventListener('click', function() {
city.innerHTML = places[i];
});
}
<button class="box1">One</button>
<button class="box1">Two</button>
<button class="box1">Three</button>
<button class="box1">Four</button>
<div id="name"></div>
Take special note of the use of let i instead of var i inside that for loop -- ES6 variables are scoped differently; if I had used var there then all four events would get the value of i after the loop has run (so all the buttons would be looking for places[4]!). With let or const the variable is scoped within its block, so the value you want is captured by each iteration in the loop.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Daniel Beck |
