Nike Yulistia Angreni Nike Yulistia Angreni - 6 months ago 15
Javascript Question

Set checked datatable jquery looping not working

I have code to checked data from ajax response in datatable, here it is:

kpi_id = jsonData.kpi_id;
var table_kpi_list = $('#kpi_list').DataTable();
$.each(kpi_id.split(","), function(i,e){
table_kpi_list.column(1,{ search:'applied' } ).data().each(function(value, index) {
if(value === e)
{
var rows = table_kpi_list.rows({ 'search': 'applied' }).nodes();
$('input[type="checkbox"]', rows[index]).prop('checked', "checked");
}
});
});


I got no value(try to used
console.log
), then i try to make alert into it,and it checked (All value are shown). But when i remove alert,no rows checked.

Why and how to fix it? thanks

Answer

I am guessing via alert statement i think DOM is getting enough time to get rendered completely. Hence your $(input[type...) line of code is getting executed correctly. I will suggest you to put setTimeout() around your $(input[type...) code with say 200 milli sec delay and see if you get your code working. Your code can be altered as follows:

kpi_id = jsonData.kpi_id;
 var table_kpi_list = $('#kpi_list').DataTable();
 $.each(kpi_id.split(","), function(i,e){
     table_kpi_list.column(1,{ search:'applied' } ).data().each(function(value, index) {
        if(value === e)
        {
            var rows = table_kpi_list.rows({ 'search': 'applied' }).nodes();
            setTimeout(function(){
                $('input[type="checkbox"]', rows[index]).prop('checked', "checked");
            },200);
        }
    });
});