This question already has an answer here:
- Event binding on dynamically created elements? 14 answers
- Direct vs. Delegated - jQuery .on() 4 answers
On click on the button ADD it creates a dynamic row. Each row has a checkbox. I am using JS code to make hidden inputs for each checkbox but it is not working on dynamically created checkboxes. However if I put the checkbox outside of GetDynamicCheckBox() it works just fine.
$(document).ready(function() {
//ADD ROW
$("#btnAdd").bind("click", function () {
var div = $("<div />");
div.html(GetDynamicCheckBox());
$("#TextBoxContainer").append(div);
$(div).addClass('rowUser');
});
//USE HIDDEN INPUTS
var chk = $('input[type="checkbox"]');
chk.each(function(){
var v = $(this).attr('checked') == 'checked'?1:0;
$(this).after('<input type="hidden" name="'+$(this).attr('rel')+'" value="'+v+'" />');
});
chk.change(function(){
var v = $(this).is(':checked')?1:0;
$(this).next('input[type="hidden"]').val(v);
});
//DEFINE A ROW
function GetDynamicCheckBox() {
return '<label class="switch"><input data-rel="active" value="false"name="DynamicYesNoStart11" class="switch-input" type="checkbox" /><span class="switch-label" data-on="Yes" data-off="No"></span> <span class="switch-handle"></span></label> '
}
});
I was reading many similar questions but I couldn't made my code to work.
Aucun commentaire:
Enregistrer un commentaire