Home » Javascript » jQuery – Child-row td below th rather than on the left (aligning)

jQuery – Child-row td below th rather than on the left (aligning)

Posted by: admin August 19, 2018 Leave a comment

Questions:

I am trying to create a separate sub table to appear directly below that row. I was able to do this; however, I am having hard time aligning the header and data of that sub table. My header is in the same row as my sub table data; I want them in a different row where the header is above the data (td).
For example:

Description Arrival

Heavy

Can someone guide me what I am doing wrong when I am appending the sub table headers?

HTML:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="parentTable">
  <thead>
    <tr class="category">
      <th>Unique ID</th>
      <th>Name</th>
      <th>Email</th>
      <th>Price</th>
      <th>Hours</th>
    </tr>
  </thead>

  <tbody id="parentTableBody">
  </tbody>
</table>

jQuery:

$(document).ready(function() {
  var arr1 = generateItem();
  if (arr1) {
    var arr2 = [].concat(arr1);
    var tr;
    $.each(arr2, function(i, e) {
      tr = $('<tr>');
      //TODO only add <a> tag if there is going to be a child row!
      tr.append("<td>" + "<a href='#'>" + (e.UniqueId || "") + "</a>" + "</td>");
      tr.append("<td>" + (e.Name || "") + "</td>");
      tr.append("<td>" + (e.Email || "") + "</td>");
      tr.append("<td>" + (e.Price || "") + "</td>");
      tr.append("<td>" + (e.Hours || "") + "</td>");
      $('#parentTableBody').append(tr);

        tr = $('<tr class="child-row">');
                 tr.append("<th>" + "Description" + "</th>");
             tr.append("<th>" + "Arrival" + "</th>");
             tr.append("<td>" + (e.Description || "") + "</td>");
             tr.append("<td>" + (e.Arrival || "") + "</td>");
             $('#parentTableBody').append(tr);  
             tr.hide();

    });

  }
});

function generateItem() {
  var item = [{
      UniqueId: "0",
      Name: "Alex",
      Email: "[email protected]",
      Price: "$20.00",
      Hours: "1",
      Description: "N/A",
      Arrival: "Noon"
    },
    {
      UniqueId: "1",
      Name: "Jay",
      Email: "[email protected]",
      Price: "$12.00",
      Hours: "0.2",
      Description: "Small",
      Arrival: "test"
    },
    {
      UniqueId: "2",
      Name: "Dylan",
      Email: "[email protected]",
      Price: "$32.00",
      Hours: "2.2",
      Description: "Heavy"
    }
  ];

  return item;
}

$(function() {
  $('#parentTable tbody a').on("click", function(event) {
      $baseRow = $(event.target).closest("tr");
      next = $baseRow.next("tr");
      if (next.is(".child-row")){
        next.toggle();
      }

  });
});

jsFiddle Demo

Answers: