Looping multiple datatables on the same page

Looping multiple datatables on the same page

gcc_andregcc_andre Posts: 4Questions: 2Answers: 0

I have the following issue:

I have multiple datatables on the same page, different IDs, different data-action and some of them, receives its data from ajax.

I could not find a way to not hard code the datatable js variables in jQuery, I want to know a way to loop out the datatables found in the page, fetch the data-action and add to its respective id

I tried something like

var theAjaxURL = '[the_ajax_url];'

$.each($('.datatable'), function () {
        var dt_id = $('.datatable').attr('id');
        var dt_action = $('.datatable').data('action');
        if (typeof dt_action !== typeof undefined && dt_action !== false) {
            var dt_ajax = theAjaxURL + '?action=' + dt_action;
            $('#' + dt_id).DataTable({
                retrieve: true,
                ajax: dt_ajax,
         } else {
            var table = $('.datatable').DataTable({
                retrieve: true,
                responsive: true,
            });
        }

    });

but did not worked well.

This question has an accepted answers - jump to answer

Answers

  • colincolin Posts: 15,115Questions: 1Answers: 2,583

    Hi @gcc_andre ,

    When you said it "did not worked well", were you seeing console errors? Were the tables not initialising? At a glance the code looks like it should be doing what you want.

    We're happy to take a look, but it would help, as per the forum rules, if you could link to a running test case showing the issue so we can offer some help. Information on how to create a test case (if you aren't able to link to the page you are working on) is available here.

    Cheers,

    Colin

  • gcc_andregcc_andre Posts: 4Questions: 2Answers: 0

    http://live.datatables.net/temuvori/2/edit

    There you go, the thing I wanted to change is the data-action for each of database table but because of the structure of the json, I could not use different urls

    As you see, what I want:
    - Loop each datatable with its data (action / id)
    - Put the ajax on its respective datatable ID

    Thanks for helping!

  • colincolin Posts: 15,115Questions: 1Answers: 2,583
    Answer ✓

    Hi @gcc_andre ,

    This has it working: http://live.datatables.net/holekelu/1/edit

    The problem was because you were always accessing the first table's ID. By using $(this), you're getting the one specifically for that iteration.

    Cheers,

    Colin

This discussion has been closed.