shanebp
shanebp

Reputation: 1956

jQuery - cannot get value of dynamically added checkbox

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?

Upvotes: 1

Views: 57

Answers (1)

Ivan86
Ivan86

Reputation: 5708

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.

Upvotes: 1

Related Questions