0

I have a database that outputs a table in a single row, I need to use jQuery to split the single row into multiple rows of three columns, it would also be good if I could change a value to make it multiple rows of 4 or 5 in the future.

HTML Output example

<table class="staff">
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td>7</td>
      <td>8</td>
      <td>9</td>
      <td>10</td>
      <td>11</td>
      <td>12</td>
      <td>13</td>
    </tr>
  </tbody>
</table>

Result required

enter image description here

Note, I can not write jQuery, so I manipulate exisiting scripts, I have found the script below, it creates multiples of 2 columns per row however when I try and mess with the values I can't get it to display 3 columns per row.

jQuery

$("table.staff td").each(function(index) {
  var odd = isOdd((index + 1));
  if (odd) {
    $("table.staff tbody").append($("<tr>"));
  }
  $("table.staff tr").last().append($(this));
});
$("table.staff tr").first().remove();

function isOdd(num) {
  return num % 2;
}

fiddle

Any help would be appreciated

Thanks

2 Answers 2

3

You can get all the td and then use the splice() get the desired number of items per row, and then append them to the tbody

$(document).ready(function() {
  let tds = $('td');
  let len = tds.length;
  let itemsPerRow = 3;
  for (var i = 0; i < len; i = i + itemsPerRow) {
    $('tbody').append($('<tr></tr>')).append(tds.splice(0, itemsPerRow));
  }
});
<script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"></script>

<table class="staff" border="1">
  <tbody>
    <tr>
      <td>1</td>
      <td>2</td>
      <td>3</td>
      <td>4</td>
      <td>5</td>
      <td>6</td>
      <td>7</td>
      <td>8</td>
      <td>9</td>
      <td>10</td>
      <td>11</td>
      <td>12</td>
      <td>13</td>
    </tr>
  </tbody>
</table>

Sign up to request clarification or add additional context in comments.

2 Comments

Hi, just noticed when I used your solution in my project the source code of the table doesn't look correct, there are <tr></tr> between the td's not on either side, could you possibly have a look.
Don't worry, fixed it.
0

I used the existing solution in my project. The source code of the table doesn't look correct. There are <tr></tr> tags between the TD tags, not on either side. Could someone possibly have a look?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.