MuhFred MuhFred - 19 days ago 7
Javascript Question

Set checkboxes to checked based on Ajax GET request

I'm trying to get the checkboxes checked based on data coming from the server through an ajax get request:




var GetTodos = (function () {
//GET/READ
return $.ajax({
url: '/api/Todos/GetTodos',
contentType: 'application/json',
success: function (todos) {
var tbodyEl = $('tbody');
$.each(todos, function (i, todo) {
if (!todo.isCompleted)
$('#myCheckbox').prop('checked', false);
else
$('#myCheckbox').prop('checked', true);
tbodyEl.append('\
<tr>\
<td><input type="checkbox" value="'+todo.id+'" id="myCheckbox" checked/></td>\
<td class="id">' + todo.id + '</td>\
<td><input type="text" class="name" value="' + todo.text + '"></td>\
<td>\
<button id="editBtn" class="btn btn-warning">Update</button>\
<button id="deleteBtn" class="btn btn-danger">Delete</button>\
</td>\
</tr>\
');
});
}
});
});





So i'm sending an ajax get request to get json data and the following response is this




[
{
"id": 1,
"text": "Walk the dog",
"isCompleted": false
},
{
"id": 4,
"text": "go out with friends",
"isCompleted": false
},
{
"id": 5,
"text": "touch the fishy",
"isCompleted": true
}
]





This is what I ended up with




enter image description here




So the checkboxes doesn't get checked properly. If someone can help me out with this it will be much appreciated, thanks.

Answer

Working fiddle.

First of all id should be unique in same document, so in your case replace id myCheckbox by class.

And the checked true and false the both will check the input you should add attribute checked just in case you want to check :

$.each(todos, function (i, todo) {
    var checked = '';

    if (todo.isCompleted)
        checked = 'checked';

    tbodyEl.append('\
        <tr>\
            <td><input type="checkbox" value="'+todo.id+'" class="myCheckbox" '+checked+'/></td>\
            <td class="id">' + todo.id + '</td>\
            <td><input type="text" class="name" value="' + todo.text + '"></td>\
            <td>\
                <button id="editBtn" class="btn btn-warning">Update</button>\
                <button id="deleteBtn" class="btn btn-danger">Delete</button>\
            </td>\
        </tr>\
    ');
});

Hope this helps.