0

I have a function that dynamically creates div elements based upon whatever input is given, and lets them choose certain items by clicking on each div. I have it so that if the div is clicked, a function (named checkToggle) is called that makes it looks like it is selected and adjusts some related variables. There is a checkbox in the div element that is toggled by this function (hence its name). Long story short, I had to jump through some hoops to get it to work, most of which I don't even remember. Please don't ask me about that.

The point of this question is this. I initially used the following JavaScript code to run the function when the checkbox was clicked. It was assigned by the main function, which created these div elements using a for loop.

document.getElementById(`${itemID}-checkbox`).onclick = function() {
    checkToggle(`${itemID}-checkbox`);
};

This works, but I wanted to try to convert all of my onClick functions to JQuery. Here is the JQuery alternative I created.

$(`${itemID}-checkbox`).on(`click`, function() {
    checkToggle(`${itemID}-checkbox`);
});

While the code itself seems to be fine, it does not work. It seems as if JQuery functions cannot be created like this in a for loop or something. It is applied after the element is created and put in its place, so I don't think it has anything to do with the element not being ready. I am also having the same issue with 2 other similar cases. Any idea as of why this isn't working?

Let me know if more information is needed and if so, what kind of information is needed.

  • If you're using template strings, why are you still doing concatenation? Use `\`${itemID}-checkbox\`` – Barmar Aug 25 '18 at 01:09
  • The callback function receives the element you clicked on as `this`. You shouldn't need to use `itemID+'-checkbox'` inside the function, just use `this.id`. – Barmar Aug 25 '18 at 01:12

1 Answers1

2

You need to update the selector to Target HTML id using the # character. Simply prepend the character to the query:

$(`#${itemID}-checkbox`).on(`click`, function() { checkToggle(`${itemID}-checkbox`); });

It would also apply to DOM methods querySelector or querySelectorAll as well.

Hopefully that helps!

Alexander Staroselsky
  • 37,209
  • 15
  • 79
  • 91