Loop through each row in the Datatable and access the details or child

I need to iterate through each child row in a datatable.

For example, if I have AJAX data structured like this:

"data": [
{
  "date"      : "1/17/2016",
  "supplier"  : "supplier1",
  "total"     : "$10",
  "payment"   : "Cash",
  "product" : Array[2] 
     0: "product1"
     1: "product2"
  "price" : Array[2]
     0: "$5"
     1: "$5"
},
{
  "date"      : "2/1/2016",
  "supplier"  : "supplier2",
  "total"     : "$3",
  "payment"   : "Cash",
  "product" : Array[1] 
     0: "product1"
  "price" : Array[1]
     0: "$3"
},
{
  "date"      : "1/17/2016",
  "supplier"  : "supplier3",
  "total"     : "$15",
  "payment"   : "Cash",
  "product" : Array[3] 
     0: "product1"
     1: "product2"
     2: "product3"
  "price" : Array[2]
     0: "$3"
     1: "$5"
     2: "$7"
},

I want to create a child row in the datatable for the product & price arrays. You can see an example of what I'm aiming for in the following link: here.

To customize the formatting, I only need to edit the script within the function format as follows:

function format ( d ) {
    // `d` is the original data object for the row
    return '<table class="table table-border table-hover">'+
      '<tr>'+
         '<td>Product</td>'+
         '<td>Price</td>'+
      '</tr>' +

      '<?php 
          $loop = 5; 
          echo $loop;             <-- here

          for ($i=0; $i<$loop; $i++) {                      
             echo "<tr><td>'+d.product['$i']+'</td> <td>'+d.price['$i']+'</tr>"; 
       } ?>' +

    '</table>';
}

Everything runs smoothly, and the data displays correctly, but I have to manually define the variable $loop.

I attempted to set $loop = "'+d.product.length+'", which should dynamically determine the length of the product array, but when entering the loop, it seems that $loop becomes 0 as no rows are displayed.

Additionally, when I try using

'"+d.product_.length+"' + '"+d.product_.length+"'
and then printing $loop, it results in 33 when the product array count is 3. However, changing the operation to addition instead of concatenation yields a result of 0.

If anyone has a solution to this issue so I can accurately determine how many iterations my script should perform, please let me know. Your help would be greatly appreciated!

Answer №1

A great way to enhance your table with additional data is by utilizing jquery's $.each function instead of relying on php loops. To do this effectively, ensure that you structure your table body beforehand and then use the append method as shown below:

/* Custom formatting function for row details - adjust according to your requirements */
function format ( d ) {
    console.log(d.product);
    var trs=''; // variable used for construction
    $.each($(d.product),function(key,value){
        trs+='<tr><td>'+value+'</td><td>'+d.price[key]+'</td></tr>';
        // iterates through each product and appends it to trs, assuming price values array matches product count
    })
    // `d` represents the original row data object
    return '<table class="table table-border table-hover">'+
           '<thead>'+
              '<th>Product</th>'+
                '<th>Price</th>'+  
           '</thead><tbody>' 
               + trs +
        '</tbody></table>';
}

$(document).ready(function() {
    var table = $('#example').DataTable({
        "ajax": 'https://raw.githubusercontent.com/kshkrao3/JsonFileSample/master/Employees.json',
        "columns": [
            {
                "class":          'details-control',
                "orderable":      false,
                "data":           null,
                "defaultContent": ''
            },
            { "data": "date"},
            { "data": "supplier"},
            { "data": "total"},
            { "data": "payment"}
        ]
    });

    // Event listener for expanding and collapsing row details
   $('#example tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row( tr );

        if ( row.child.isShown() ) {
          // Closes the open row if already expanded
          row.child.hide();
          tr.removeClass('shown');
        }
        else {
          // Expands the selected row
          row.child( format(row.data()) ).show();
          tr.addClass('shown');
        }
    });
});

Note: A correction was made in your click event.. You were referencing dTable.row in the event, but it should be table.row since you have stored the reference in the table variable.

VIEW DEMO

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Creating a distinctive appearance for JavaScript's default dialogue box

Is there a way to enhance the design of my code that prompts the user for input using JavaScript's `prompt`? Currently, it appears too simplistic. Are there any CSS or alternative methods to improve its appearance? function textPrompt(){ var text = ...

How to retrieve the changing input value in ReactJS using Jquery/JS

I have a form in WordPress with two input range sliders. The form calculates the values of these sliders and displays the result as shown below: <input data-fraction-min="0" data-fraction="2" type="hidden" data-comma=" ...

Using a URL in the fill property is a simple process that involves specifying

Here is the snippet of the code I'm working with: <?xml version="1.0" standalone="no"?> <html> <head> <style> .someClass { fill:"url(#Pattern)"; } </style> ...

What is the process for deleting an animation using JavaScript, and how can the background color be altered?

Two issues are currently troubling me. First off, I am facing a challenge with an animation feature that I need to modify within the "popup" class for a gallery section on a website. Currently, when users load the page, a square image and background start ...

How can I adjust the animation speed for ChartJS graphics?

Trying to adjust the animation speed of a pie chart in chartJS. Various methods have been attempted: numSteps: Number animationSteps: Number Chart.defaults.global.animationSteps = Number However, none of these approaches have successfully altere ...

Submitting the form does not result in the textbox being cleared

I have been attempting to clear the txtSubTotal text box upon clicking the PROCEED button, but it seems that my efforts have been in vain despite trying various code examples, including those from SO. btnProceed/HTML <input type="submit" name="btnProc ...

Is there a way to fetch API data selectively rather than all at once?

Hello everyone, I successfully managed to retrieve data from the Star Wars API in JSON format and display it on my application. Initially, I set the state as 'people.name' to obtain the name object. However, this also rendered unwanted data when ...

substitute tags

Is there a way to change the tagName of a tag using jQuery? For example, if I have an HTML document and I want to replace all 'fieldset' with 'div'. Any suggestions would be appreciated! ...

Using a URL in an AJAX request

Before redirecting to another page, I am storing data from a textbox. When the user clicks the back button on the page load function in JavaScript, I retrieve the data from the textbox using: var pageval = $('#grid') .load('/Dealer/AllClai ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

I need help figuring out how to send a POST/GET request from AJAX to a custom module controller in Odoo 10, but I'm running into issues

I have implemented a custom module in Odoo 10 with a simple controller. Everything works smoothly when accessing http://127.0.0.1:8069/cmodule/cmodule through the browser, displaying the expected return string. However, I encountered an issue when attempt ...

Executing a cloud function in Firebase from an Angular-Ionic application by making an HTTP request

I am a newcomer to GCP and app development, so please bear with me if this question seems mundane. Currently, I have an angular-ionic app that is connected to Firebase allowing me to interact with the Firestore database. Now, my challenge is to invoke a ht ...

What is the method for reverting style properties back to their CSS defaults using Javascript?

The php-generated page contains multiple elements structured like this: <td class="defaultTDStyle" style="color:userDefinedCustomColor" id="myTDId"></td> There is a default style in place with additional styles ap ...

Handling a WCF POST request with JQuery resulting in a 400 Bad Request HTTP Response

I'm encountering an issue with my JQuery POST not being accepted by the WCF Service. Below is the JavaScript code for the POST: function jqueryPost() { var url = "/LoggingTest"; $.post(url, { message: "test message" }); } To handle the POST ...

Tips for utilizing node.io for HTML parsing with node.js?

Struggling to utilize node.io with node.js for parsing an HTML page stored as a string in a variable. Encountering difficulties passing the HTML string as an argument to my node.io job. Snippet from my node file nodeiotest.js: var nodeIOJob = requi ...

Array vs Single Object - Comparing AngularJS / Javascript Data Structures (Basic)

My array is very basic [ { ticketId: 1, name: "John", }, { ticketId: 124, name: "Ads" } ] I have displayed the data in a dropdown menu <ul class="dropdown-menu"> <li ng-repeat="ticket in tickets"> <a h ...

Unexpected lag causing delays in jQuery animations

I am attempting to implement a "hover" effect using jQuery. Everything seems to be working fine, except for a strange delay that occurs only the first time the complete callback is triggered - oddly enough, this is the only instance where it reaches the pr ...

"The debate over using 'stringly typed' functions, having numerous redundant functions, or utilizing TypeScript's string enums continues to divide the programming

I have a specific object structure that contains information about countries and their respective cities: const geo = { europe: { germany: ['berlin', 'hamburg', 'cologne'], france: ['toulouse', ' ...

"An error occurred: Uncaught SyntaxError - The import statement can only be used within a module. Including a TypeScript file into a

I need to integrate an Angular 10 TypeScript service into a jQuery file, but I am facing an issue. When I try to import the TypeScript service file into my jQuery file, I encounter the following error: Uncaught SyntaxError: Cannot use import statement outs ...

Swiper JS eternal carousel transition

While trying to create an endless carousel using swiper js on my website, I encountered a slight vibration between the slides that makes it seem like the images are flickering. Despite my efforts, I have been unable to find a solution to this issue. Any as ...