0

I'm new to javascript. I'm trying to use an alert that shows button data when clicking a specific button.

But here it's just alerting same button name always. How to fix that?

function getElement(k) {
  var elm = document.getElementById(k);
  /*alert ("hai");*/
  return elm;
}

for (var i = 1; i <= 6; i++) {
  getElement("button" + i).addEventListener("click", function() {
    alert("clicked on button" + i);
  });
}
li {
  list-style: none;
}
<li>
  <div class="button-holder"><button id="button1" class="button">button1</button>
  </div>
</li>
<li>
  <div class="button-holder">
    <button id="button2" class="button">button2</button>
  </div>
</li>
<li>
  <div class="button-holder">
    <button id="button3" class="button">button3</button>
  </div>
</li>
<li>
  <div class="button-holder">
    <button id="button4" class="button">button4</button>
  </div>
</li>
VLL
  • 9,634
  • 1
  • 29
  • 54
ADH - THE TECHIE GUY
  • 4,125
  • 3
  • 31
  • 54
  • `"Uncaught TypeError: Cannot read property 'addEventListener' of null"` – CertainPerformance Jul 12 '18 at 08:46
  • 2
    This is a "closure thing" (your functions get the "live" value of `i`), see the comments above. Anyway, you probably will be well served to learn about `console.log()` for debugging instead of `alert()` – John Hascall Jul 12 '18 at 09:01

2 Answers2

0

function getElement(k) {
  var elm = document.getElementById(k);
  /*alert ("hai");*/
  return elm;
}

for (var i = 1; i <= 6; i++) {
  getElement("button" + i).addEventListener("click", function() {
    alert("clicked on button" + i);
  });
}

Actually, whenever you are calling addEventListener inside the for loop, you are going on adding the click listeners to your button and also incrementing i value(Which should be < 5, there are no 5th or 6th buttons. Hence one error is being shown as Uncaught TypeError: Cannot read property 'addEventListener' of null ).

So whenever you are clicking a button, since the i value is already stuck at 5 so it always alerts: "Clicked on button5".

What you should rather do to fix this error is:

 

var btn = document.querySelectorAll('.button');

 for(var i = 0; i < btn.length; i++) {
   btn[i].addEventListener("click", function(){
     alert("Clicked on " + this.innerText);
   });
 }
amiyakt
  • 15
  • 6
0

As per this answer, you simply need to use let instead of var in Miaan's solution:

for (let i = 1; i < 5; i++) {
document.getElementById("button" + i).addEventListener("click", function() {
console.log("clicked on button" + i);
alert("clicked on button" + i);});
}

Or you can also replace var in your for loop to let. Should work the same.

mythr
  • 80
  • 1
  • 10