can you help me how to load checked checkbox in edit modal? I'm using checkbox to input multiple roles in my system. Everything was fine but I have problem in my edit modal. The checkbox was blank and not checked.
this is my ajax edit function:
function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
$('#editModalForm input[name=role_id]').prop('checked', true);
}
}
}
});
}
this is my checkbox in html form
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id[]"
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>
this is my json result:
[{"id":288,"role_id":["2","3"],"email":"me@gmail.com"}]
function edit_function(task, id) {
$('#editModal').modal();
$.ajax({
method: 'POST',
url: '<?php echo base_url() . 'user/edit/' ?>' + id,
dataType: 'json',
success: function(x) {
if (resp.length > 0) {
for (var i = 0; i < resp.length; i++) {
id= x[i]['id'];
$("#editModalForm input[name=email]").val(x[i]['email']);
for (var r = 0; r < x[i]['role_id'].length; r++) {
var role=x[i]['role_id'][r];
$('#role_id_'+role).prop('checked', true);
}
}
}
}
});
}
<?php foreach ($roles as $row) : ?>
<div class="form-check-inline">
<label class="form-check-label">
<input type="checkbox" name="role_id[]" id="role_id_<?php echo $row->role_id ?" />
value="<?php echo $row->role_id; ?>"><?php echo $row->role_id; ?>
</label>
</div>
<?php endforeach; ?>