<html>
<head runat="server">
<title>bind CheckboxList using Jquery and ajax</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<script>
$(document).ready(function () {
var checkedvalue = [];
$.ajax({
type: "POST",
url: "Default2.aspx/GetRole",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var json = JSON.parse(data.d);
var val = 0;
var table = $('<table></table>');
var option = json.map(x =>
table.append($('<tr></tr>').append($('<td></td>').append($('<input>').attr({
type: 'checkbox', name: 'chkRoles', value: x.chkName, id: 'chkrole' + val
}))).append(
$('<label>').attr({
for: 'chkRoles' + val++
}).text(x.chkName))));
$('#chkrole').append(table);
}
});
$("#btnget").click(function () {
checkedvalue = [];
$("input[name=chkRoles]").each(function () {
if ($(this).is(":checked")) {
checkedvalue.push($(this).val());
}
});
$("#lblSelected").text(checkedvalue);
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<span>Checkbox list</span>
<div id="chkrole">
</div>
<br />
<input type="button" value="Get value" id="btnget" />
<br />
<span id="lblSelected"></span>
</div>
</form>
</body>
</html>