Skip to content Skip to sidebar Skip to footer

Jquery .change() Method Does Not Work For Dynamically Created Check-box

I have to create a cascade of elements dynamically.

Solution 1:

You can use jquery on for doing that:

$("#chkoffre").on("change", function(){
    alert( 'CheckboxOffre' ); // or $(this).val()if($(this).is(":checked")) {

   }else{

   }
});

This known as event delegation.

Solution 2:

In order to listen for an event on an element that has been dynamically added to the DOM, you have to use a event delegate and not a directly bound event handler. As mentioned in the jQuery api documentation for .on, "Event handlers are bound only to the currently selected elements; they must exist at the time your code makes the call to .on()". http://api.jquery.com/on/ This is true for .change and other direct bound event types.

So this:

$("#chkoffre").change(function () {

Must be changed to this:

$("#select_prix").on("change", "#chkoffre", function () {

Here's a fiddle that demonstrates this fix when applied to your code: https://jsfiddle.net/uuvcyf9o/ Here's the full code:

$('#prix').on('change', function() {
    if ($(this).val() < 2) {
        $("#select_prix").empty();
    }  

    var stroffre  ='<label class="col-sm-2 control-label text-primary">Offre ?</label>';
    stroffre +='<div class="checkbox col-sm-10">';
    stroffre +='<label class="checkbox-custom" data-initialize="checkbox">';
    stroffre +='<input class="sr-only" id="chkoffre" type="checkbox" value="">';
    stroffre +='<span class="checkbox-label">Autoriser les  offres</span>';
    stroffre +='</label></div>';

    if ($(this).val() == 2) {
        $("#select_prix").append(stroffre);
    }
});

$("#select_prix").on("change", "#chkoffre", function () {
    alert( 'CheckboxOffre' ); // or $(this).val()if($(this).is(":checked")) {
    }else{
    }
});

Post a Comment for "Jquery .change() Method Does Not Work For Dynamically Created Check-box"