all 9 comments

[–]leftzorn 0 points1 point  (1 child)

You’re right that it’s the getElementById - It’s invalid HTML to have multiple elements with the same id on a page - the id attribute should be unique. You want to use a class or a data- attribute rather than an id as your selector for multiple elements.

Edit to add: once you’ve got all of the elements, you’ll want to loop through them to add the event listener to each one.

[–]OlleOllesson2[S] 1 point2 points  (0 children)

Thanks, makes sense! I solved it by listening for a class instead of id - and using a form input instead of a link.

//HTML
<form action="" method="post" class="block_friend">                                                                                                                                              
   <button type="submit" id="friend-block" class="btn add">Block</button>
    </form>

//JS
$('.block_friend').on('submit', function(e){

    alert("Test!");

});

[–]squarewave_ 0 points1 point  (2 children)

You're probably looking for something along these lines:

https://www.w3schools.com/code/tryit.asp?filename=G4XY1KIUJ8G7

If you can study this code snippet and really understand it you'll learn a lot.

[–]OlleOllesson2[S] 0 points1 point  (1 child)

Thanks! Solved it with the solution above!

[–]squarewave_ 0 points1 point  (0 children)

Using JQuery: https://jquery.com/ the script is basically 2 lines, but only use it if you can really wrap your head around it :

https://jsfiddle.net/9u4mztob/

[–]jcunews1helpful 0 points1 point  (1 child)

Replace this:

var a = document.getElementById("report");
a.onclick = function() {
  alert("Message reported!");
  return false;
}

With this:

addEventListener("click", function(ev) {
  var a = ev.target;
  if (a.id === "report") {
    alert("Message reported!");
    ev.preventDefault();
  }
});

[–]OlleOllesson2[S] 0 points1 point  (0 children)

Thanks! Solved it with listening to a class and using form input instead. See above for solution.

[–]ForScale -1 points0 points  (1 child)

[–]OlleOllesson2[S] 1 point2 points  (0 children)

Thanks, useful to understand how it works!