Home > front end >  .each(function()) not looping at loading page but yes a refreshing with dedicated button
.each(function()) not looping at loading page but yes a refreshing with dedicated button

Time:03-17

I've been making a page to load a list of tasks from a database, it works fine.

I've been asked to add a title on hover to check description without having to click on a task, for easy management.

I've done that by looping each tr in a table and adding the title with .attr('title','test');.

This is the code:

console.log("runs?");
that.tableSalidas.row(this).$('tr').each(function(){
    data =  that.tableSalidas.row(this).data();
    $(this).attr('title', data.observaciones);
    console.log("Working..");
});
console.log("yes...");

The console only prints out:

runs?
yes...

Only after I hit a reload button I have, or a timer I have set up calls on the api again, the title will be added and the console.log i have in the loop logs...

runs?
(3) Working..
yes...

adding the titles too...

Title working

CodePudding user response:

As written in a previous comment, the code block seems to be executed before the datatable gets filled with data. So it needs to be delayed to when it is guaranteed that the data is there. Check out the init event: https://datatables.net/reference/event/init

Something like the following should work:

that.tableSalidas.on('init', function () {
    console.log("runs?");
    that.tableSalidas.row(this).$('tr').each(function(){
        data =  that.tableSalidas.row(this).data();
        $(this).attr('title', data.observaciones);
        console.log("Working..");
    });
    console.log("yes...");
});
  • Related