0

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++;
        }
    });

}

aynber
  • 22,380
  • 8
  • 50
  • 63
  • Welcome to Stack Overflow! We'll help you when you get stuck, but we won't write your code for you. Give it a try yourself first, please, and come back when you have a specific question. – Daniel Beck Feb 03 '22 at 12:34

1 Answers1

0

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.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53