Habib Rehman Habib Rehman - 28 days ago 6
jQuery Question

Couldn't get id of dynamically created checkbox

I have check boxes dynamically created, on each clone i increment the id of the checkbox and put the same name to the class of the div on which i want to perform action after checking that checkbox.

Now the problem is that when checkbox is cloned with new id on clicking that new box the alert doesn't work even though i have same class on both old and new check boxes.
I haven't pasted the clone js code but it's working correct all fields are getting cloned with new id's and classes.

Here is the snippet for checkbox html and JS.

*****************************EDIT*************************************


i have tried using dynamic change function but it doesn't work


$(document).on('change', ".check_chauffer", function(){
alert(this.id);
});




var chauffeur_index = $('.check_chauffer').length - 1;
$('.check_chauffer').last().attr('id', 'Chauffeur_details_' + chauffeur_index);
$('.Chauffeur_details').last().addClass('Chauffeur_details_' + chauffeur_index);

$(function() {
$(".check_chauffer").change(function() {
alert(this.id);
if ($(this).is(":checked")) {
$('.' + this.id).removeClass("hidden");
} else {
$('.' + this.id).addClass("hidden");
}
});
})

.hidden {
display: none;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<input type="checkbox" class="check_chauffer" id="Chauffeur_details_0" name="check_chauffer">Chauffeur
<div class="clearfix"></div>
<input type="checkbox" class="check_airport" name="check_airport" id="airport_details_0">Airport
<span class="help-block"></span>

<div class="Chauffeur_details_0 hidden">
<div class="col-md-2 booking_details">
<h6><strong>Booking Details:</strong></h6>
</div>
<div class="col-md-2">
<label for="">Per Hour Rate</label>
<div class="input-group">
<input type="number" name="Chauffeur_per_hour_rate[]" class="form-control " required="required">
</div>
</div>
<div class="col-md-2">
<label for="">Min Hours/Day</label>
<div class="input-group">
<input type="number" name="Chauffeur_min_hours_booking[]" class="form-control " required="required">
</div>
</div>
<div class="col-md-2">
<label for="">Max Hours/Day</label>
<div class="input-group">
<input type="number" name="Chauffeur_max_hour_perday[]" class="form-control" required="required">
</div>
</div>
</div>





if anyother code is required please ask me.

Answer

Your first issue is, you should add a delegate to the event handler.

The .on() method allows you to delegate any desired event handler to: current elements, or any future elements which might be added to the DOM in a later time.

$( document ).on( 'click', '.check_chauffer', function() {
    alert(this.id);
});

The second thing is to make sure you add it in document.ready.

$( document ).ready(function() {
    $( document ).on( 'click', '.check_chauffer', function() {
        alert(this.id);
    });
});