-3

the node <'ul'> I received asynchronously contains <'li'> inputs. I need to add event to every li.

<ul class="parent">
  <li><input id="red" type="checkbox"></li>
  <li><input id="black" type="checkbox"></li>
  <li><input id="white" type="checkbox"></li>
</ul>

As I understand I need to use smth like:

$(document).on('change', '.parent' ....}) 

And probably I need .each.
Can you describe how to use this functionality in this certain case?

Rurohi53
  • 90
  • 6
  • 1
    `$(document).on('change', '.parent input' ....})` – Flash Thunder Sep 13 '21 at 12:40
  • 1
    You don't need .each. Use `$(document).on('change', '.parent input', function() {})` and use `this` / `$(this)` inside the handler to get the ``. – ChrisG Sep 13 '21 at 12:41
  • 1
    You don't even need `$(document)` just `$('.parent input').change(function() {})` will work – Andrew Corrigan Sep 13 '21 at 12:43
  • 1
    @AndrewCorrigan The `
      ` is added dynamically; your solution requires to reassign the event handler each time the list is loaded. Delegating doesn't.
    – ChrisG Sep 13 '21 at 12:44
  • 1
    Duplicate: [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – ChrisG Sep 13 '21 at 12:45

2 Answers2

1

$('.parent').on('change', 'li input', function()})

0

You can attach the event handler to only parent element, the .parent, and the event only needs to bubble up from the clicked li to ul:

$('.parent').on('change', 'li > input:checkbox', function(){...});

Demo:

$('.parent').on('change', 'li > input:checkbox', function(){
  console.log($(this).attr('id'));
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="parent">
  <li><input id="red" type="checkbox"></li>
  <li><input id="black" type="checkbox"></li>
  <li><input id="white" type="checkbox"></li>
</ul>
Mamun
  • 62,450
  • 9
  • 45
  • 52