lewis4u
lewis4u

Reputation: 15047

How to set a listener on array of checkboxes in jQuery?

Situation:

Trying to 'collect' all checkboxes with this:

let docChildPermissions = $('input.docPermission').not('.parent');

And that works.

Now I just want to make an action if any of these checkboxes is changed like this;

$(document).on('change', $(docChildPermissions), function() {
    console.log($(this));
});

But in console I get this:

init [document, context: document]
0: document
context: document
length: 1
__proto__: Object(0)

This is the whole document that gets 'console logged' and I need only that selected checkbox.

Upvotes: 2

Views: 73

Answers (1)

Rory McCrossan
Rory McCrossan

Reputation: 337620

If you check the documentation for on() you'll see that the selector argument has to be a string, not a jQuery object as in your example. This is the cause of the problem.

To fix this, convert the object to a string selector, like this:

$(document).on('change', 'input.docPermission:not(.parent)', function() {
  console.log($(this));
});

Upvotes: 3

Related Questions