mardi 19 juillet 2016

Dynamically Created Checkbox Event doesn't trigger using jQuery [duplicate]

This question already has an answer here:

.html code

<div class="dropdown">
    <button type="button" class="btn btn-default dropdown-toggle" data-toggle="dropdown">Select Username  <span class="caret"></span></button>
    <ul class="dropdown-menu" id="userOpt"> </ul>
</div>

dynamicAdding.js code

for ( i=0; i<uniqueName.length-1; ++i ) {
    $('#userOpt').append('<li><input type="checkbox" name="myCheckbox"> ' + uniqueName[i] + '</li>');
}

Till now this part works fine, i can dynamically add checkbox and its appropriate value to the right side. Now i want to trigger event on click or change but both of them failed.

I tried:

$('input[type=checkbox]').click(function() {
    alert($(':checkbox:checked').length);
});

or

$(':checkbox').click(function() {
    alert($(':checkbox:checked').length);
});

giving my checkbox a class as and then followed by code

$('.box').click(function() {
    alert($(':checkbox:checked').length);
});

or 

$('#userOpt .box').click(function() {
    alert($(':checkbox:checked').length);
});

Nothing seems to work :/ PS: I tried all these functions with non-dynamic checkbox and they work perfectly by showing alerts.




Aucun commentaire:

Enregistrer un commentaire