I am creating group of check boxes dynamically and one extra check box also for selecting all group at once that one too is generated dynamically
this is html output
<input type="checkbox" id="all">all
<br>
<input type="checkbox" name="question">a
<br>
<input type="checkbox" name="question">b
<br>
<input type="checkbox" name="question">c
<br>
<input type="checkbox" name="question">d
this is jquery
$("document").ready(function() {
$("#all").on('change', function() {
if ($(this).is(":checked")) {
$("input[type=checkbox][name=question]").prop('checked', true);
} else {
$("input[type=checkbox][name=question]").prop('checked', false);
}
});
});
this is implementation.
It works fine when checkboxes are not generated dynamically
But when they are generated dynamically code has bug
I am able to check whole group but I am not able to check single checkbox
This is dynamically generated code
$('#demo3').on('change', function() {
if ($('input[type=checkbox]:checked')) {
var value = $('input[type=checkbox]:checked').val();
alert(value);
$("#demo3").hide();
$.getJSON("json/question.json", function(jd) {
var size = jd.length;
var table = "<table><tr><th><input id=\"" + "selectall" + "\" type=\"" + "checkbox" + "\"/>" +
"</th><th>Question</th><th>Option A</th>" + "<th>Option B</th><th>Option C</th>" +
"<th>Option D</th><th>Answer</th></tr>";
for (var n = 0; n < size; n++) {
table += "<tr><td>" + "<input name=\"" + "question" + "\" type=\"" + "checkbox" + "\" value=\"" + jd[n].questionid + "\"/>" +
"</td><td>" + jd[n].question + "</td>" + "<td>" + jd[n].a + "</td><td>" + jd[n].b + "</td>" + "<td>" + jd[n].c + "</td>" +
"<td>" + jd[n].d + "</td>" + "<td>" + jd[n].ans + "</td></tr>";
}
table += "</table>";
$('#demo4').html(table);
});
}
});
$('#demo4').on('change', function() {
if ($("input[type=checkbox][id=selectall]").is(":checked")) {
$("input[type=checkbox][name=question]").prop('checked', true);
} else {
$("input[type=checkbox][name=question]").prop('checked',false);
}
});