Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
151
rated 0 times [  154] [ 3]  / answers: 1 / hits: 19358  / 9 Years ago, sun, november 15, 2015, 12:00:00

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>[email protected]</td>
<td><button class=btn btn-default>X</button></td>
</tr>

More From » javascript

 Answers
9

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.


[#64392] Thursday, November 12, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
terrence

Total Points: 120
Total Questions: 115
Total Answers: 87

Location: England
Member since Fri, May 22, 2020
4 Years ago
terrence questions
Sat, Jun 5, 21, 00:00, 3 Years ago
Wed, Jun 17, 20, 00:00, 4 Years ago
;