vendredi 21 juin 2019

Detecting checkbox status change with jQuery on checkboxes created via javascript

I'm receiving this html code via Ajax in the variable data. It contains Bootstrap 4 switches, which are basically checkboxes:

<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="3" name="details[]" id="control_id_detail_3"><label class="custom-control-label" for="control_id_detail_3">S</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="4" name="details[]" id="control_id_detail_4"><label class="custom-control-label" for="control_id_detail_4">M</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="5" name="details[]" id="control_id_detail_5"><label class="custom-control-label" for="control_id_detail_5">L</label></div>
<div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="6" name="details[]" id="control_id_detail_6"><label class="custom-control-label" for="control_id_detail_6">XL</label></div>

Then, I'm adding that html content to a div called #attribute_holder with:

$('#attribute_holder').html(data);

So at the end, I have this code:

<div id="attribute_holder">
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="3" name="details[]" id="control_id_detail_3"><label class="custom-control-label" for="control_id_detail_3">S</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="4" name="details[]" id="control_id_detail_4"><label class="custom-control-label" for="control_id_detail_4">M</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="5" name="details[]" id="control_id_detail_5"><label class="custom-control-label" for="control_id_detail_5">L</label></div>
   <div class="custom-control custom-switch"><input class="custom-control-input" type="checkbox" value="6" name="details[]" id="control_id_detail_6"><label class="custom-control-label" for="control_id_detail_6">XL</label></div>
</div>

Now, I need to detect via jQuery when the checkboxes change their state. I'm using this code:

$('#attribute_holder input[type="checkbox"]').on('change', function(){
    console.log($(this).val() + ' changed state to: ' + $(this).is(':checked'));
});

This seems to work if the html is already burnt in the html when the page is loaded. But, if I load the same html via ajax, jQuery is not detecting the change event on the checkboxes. What am I missing? Thanks!




Aucun commentaire:

Enregistrer un commentaire