0

So I was reading this SO question earlier, and I am currently trying to get a basic implementation of Unobtrusive javascript working, but I don't know where I'm struggling. Normally this is something I would struggle with for much longer until I figure it out on my own, but I'm starting to get in a bit of a time crunch...

I have a several elements within my HTML document with a class called "RMButton", and I'm trying to make all of my elements with this class call a function called "RemoveQBox" (For clarity. The QBox is a DIV element, and the objects of class "RMButton" are small buttons that remove the div from the document). RemoveQBox, is already written and works just fine when I use inline JS to call it (Ex: REMOVE), but for some reason my binding within JS isn't really working out. Anybody know what I'm missing here?

Top of my Javascript file

var DBSetFields = [];
var NumQBoxes = 1;

window.onload = function() {
    RMNodeList = document.getElementsByClassName("RMButton");
    for (var i = 0; i < RMNodeList.length; ++i) {
        console.log(RMNodeList[i]);
        RMNodeList[i].onclick = RemoveQBox;

    }
};

TLDR: How do I bind all elements of a particular class to a function in Javascript?

edit:

    function RemoveQBox(e){
    console.log("Remove");
    var RemoveButton = this; //this == e.currentTarget
    console.log(RemoveButton);
    var QBox = RemoveButton.parentNode;
    QBox.remove();
    NumQBoxes -= 1;
}
Community
  • 1
  • 1
Brandon S.
  • 306
  • 1
  • 4
  • 14
  • any error in the console ? The code seem fine, I would add `var` here : `var RMNodeList = document.. ` – Hacketo Apr 06 '16 at 14:50
  • Nothing in the console unfortunately... RemoveQBox also has a console.log statement in it that lets me know if the function was called... it was not. EDIT: Also, added `var`... didn't make a difference. – Brandon S. Apr 06 '16 at 14:54
  • the `var` is just a matter of scope, that make the variable local to the function and not global, not related to the issue. – Hacketo Apr 06 '16 at 14:58
  • that mean that the main function is not called, or `getElementsByClassName("RMButton")` return an empty list – Hacketo Apr 06 '16 at 15:02
  • Sorry, the comment I deleted was in error. I made a mistake. window.onload is in-fact being called. – Brandon S. Apr 06 '16 at 15:06
  • Thanks for letting me know the code was right. Helped me a lot in isolating the problem... so apparently it was an id10t error on my part. I accidentally turned my cache back on -_-. Everything is working now. Thanks a ton. – Brandon S. Apr 06 '16 at 15:14

0 Answers0