3

I am attempting to add event listeners to all of the buttons in an HTML document. When a button is pressed I'd like to display a simple alert. My code, which isn't working at the moment, follows:

var bns = document.getElementsByTagName("button");

function addtoev() {
  for (i = 0; i < bns.length; i++) {
    bns[i].addEventListener("click", function() {
        alert("you clicked"); 
    });
   }
}

It definitely works as such in JSFiddle by calling the method or eliminating the function line, but it's still not executing in Chrome (popups are not blocked). I post my HTML, is it possible that buttons nested in a table need to be referenced differently than buttons alone?

  <tr>
  <td>John</td>
  <td>Doe</td>
  <td>john@doe.us</td>
   <td><button class="btn btn-default">X</button></td>
  </tr> 
eabates
  • 878
  • 1
  • 8
  • 22

5 Answers5

4

you need to listen of the load event, like this:

function addtoev() {
  var bns = document.getElementsByTagName("button");
  for (i = 0; i < bns.length; i++) {
    bns[i].addEventListener("click", function() {
    alert("you clicked"); });
  }
}

window.addEventListener("load",function() {
  addtoev();
});
Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
nloomans
  • 220
  • 2
  • 11
2

better to use JQuery:

    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
    </head>
    <body>
        <input type="button" id="button1" value="button1" />
        <div>
            <input type="button" id="button2" value="button2" />
        </div>
        <input type="button" id="button3" value="button3" />

        <script src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
        <script>
            $(":button").click(function (event) {
                alert(event.target.id + ' is click!');
            });
        </script>
    </body>
    </html>
YongZPub
  • 107
  • 2
  • Thanks, I'm sure it is but I'm a student tasked with doing everything the "hard way" as a learning exercise. – eabates Nov 15 '15 at 20:25
1

Maybe you should call the method addtoev()

Olivier Boissé
  • 15,834
  • 6
  • 38
  • 56
1

with jQuery: JS Fiddle

var bns = $("button");
bns.on("click", function() {
    alert("you clicked");
});
Mi-Creativity
  • 9,554
  • 10
  • 38
  • 47
0

It seems that my problems were stemming from the fact that I was loading my JS file in the header, before all of the buttons were loading. I now have it working by loading my JS at the end of the body.

eabates
  • 878
  • 1
  • 8
  • 22