1

Using php, I add checkboxes:

<div class="member"><input type="checkbox" name="team-members[]" value="5"></div>

And I can get the id when the checkbox is selected:

$('input[name="team-members[]"]').click(function(){
    alert($(this).val());
});

I can add a checkbox to the array via ajax:

<div class="member"><input type="checkbox" name="team-members[]" value="9"></div>

But when I click the dynamically added checkbox - the alert does not fire. There are no js errors in the console. How do I get the id of the new checkbox when it is clicked?

shanebp
  • 1,904
  • 3
  • 17
  • 28
  • 1
    Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Heretic Monkey Mar 19 '21 at 21:04
  • BTW, your title makes little sense with your content, considering none of the elements have ids... – Heretic Monkey Mar 19 '21 at 21:05

1 Answers1

1

For all dynamically added elements you need to use the .on() method and not .click():

$(document).on('click', 'input[name="team-members[]"]', function() {
    alert($(this).val());
});


function addCheckBox() {
    let div = $('.member');
    let chkBx = document.createElement('input');
    chkBx.type = "checkbox";
    chkBx.name = "team-members[]";
    chkBx.value = "10";
  
    div.append(chkBx);
}

addCheckBox();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="member"><input type="checkbox" name="team-members[]" value="5"></div>

You can find a good explanation of why this is necessary here.

Ivan86
  • 5,695
  • 2
  • 14
  • 30