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.

2
  • If you're using template strings, why are you still doing concatenation? Use `${itemID}-checkbox` Commented Aug 25, 2018 at 1: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. Commented Aug 25, 2018 at 1:12

1 Answer 1

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!

Sign up to request clarification or add additional context in comments.

3 Comments

That explains it. Such a simple mistake. So I was telling it to find elements instead of IDs
Right, its a simple change, but critical. It would also apply to querySelector or querySelectorAll also
Also see stackoverflow.com/questions/1451009/… so you don't run into problems with the itemID variable in the callback.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.