row().index() not working properly in my program

row().index() not working properly in my program

mastro_dinomastro_dino Posts: 8Questions: 2Answers: 0

Hi everyone, I am using ajax and datatables to present a list of products.
When I click on one of them a child table is loaded (always through ajax) showing more infos about a product like in the image below:

As you can see the first row works just fine and with a simple console.log() It returns '0' which should indicate that the first row has been selected. The problem presents itself when selecting the other rows...

This is what I get when I select the second row. All the following rows behave in a similar way and I also noticed that the products that show the next correct index (1, 2, 3) are 30010, 30100, 30101.

This is the code I use to select and build the child table:

$('#tbl-pcodes tbody').on('click', 'tr', function () {
          const tr = $(this).closest('tr');
          //Get pcode from table and assign to 'modal-pcode'
          code = table.row(this).data().pcode;
          document.getElementById('modal-pcode').innerHTML=code;
          const tdi = tr.find('i.fa');
          const row = table.row(tr);
          //const data = table.row( idx.row ).data();
          let index = table.row(this).index();
          console.log(index);
          if (row.child.isShown() ) {
            //Close row if open
            row.child.hide();
            tr.removeClass('shown');
            tdi.first().removeClass('fa-minus-square');
            tdi.first().addClass('fa-plus-square');
          }
          else {
            //Open child row
            row.child('<table id = "tbl-nutrival'+ index +'" class="text-center text-dark table-light" style="width:100%">'+
              '<thead><tr><th>Antioxidants</th><th>Calories</th><th>Carbohydrates</th><th>Fats</th><th>Fibers</th>'+
              '<th>Lipids</th><th>Proteins</th><th>Saturated&nbsp;fats</th><th>Sodium</th><th>Sugars</th></tr></thead><tbody>'+
              '</tbody></table>').show();

Unfortunately, since my tables are all built procedurally I can't link to a test program.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,298Questions: 26Answers: 4,769
    Answer ✓

    Not sure if I'm answering your question but... The row().index() is indexed based on the order the data is loaded into the table, not the sorted order.

    Kevin

  • mastro_dinomastro_dino Posts: 8Questions: 2Answers: 0

    Ok I checked the XHR respose from the server and the data is actually in this weird order, now I feel stupid.

    Thanks for the answer Kevin!

Sign In or Register to comment.