Changing the structure of an HTML table using jQuery

I have a list of elements (X in the following examples) displayed either in a row or in a column of an HTML table.

In the HTML code point of view, I have either (horizontal display):

<table id="myTable">
  <tr>
    <td>A</td>
    <td>B</td>
    <td>C</td>
    ...
  </tr>
</table>

or (vertical display):

<table id="myTable">
  <tr>
    <td>A</td>
  </tr>
  <tr>
    <td>B</td>
  </tr>
  <tr>
    <td>C</td>
  </tr>
  ...
</table>

This HTML code is generated by the JSF component (called <h:selectManyCheckboxes/>), and thus, I do not control this HTML code.

However, I want to display a list of items in 2 columns. In other words, the HTML code of my table will be something like this:

<table id="myTable">
  <tr>
    <td>A</td>
    <td>B</td>
  </tr>
  <tr>
    <td>C</td>
    <td>D</td>
  </tr>
  ...
</table>

How to do it using jQuery?

Thanks in advance for your help.

ps: If you need to know, X is actually the input and label, i.e.:

<td><input .../><label .../></td>
+3
source share
3 answers

, , , , . , ...

var idx = 1;
var row, next;
while((row = $('#myTable tr:nth-child(' + idx++ + ')')).length) {
    if((next = $('#myTable tr:nth-child(' + idx + ')')).length) {
        row.append(next.find('td'));
        next.remove();
    }
}
+2

. , , , . , .

, , .

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
    <title>Example of restructuring tables</title>
    <script src="Scripts/jquery-1.2.6.commented.js"></script>
</head>
<!--<body><table id="Table1">
  <tr>
    <td>1</td>
    <td>2</td>
    <td>3</td>
    <td>4</td>
  </tr>
</table>-->
<table id="myTable">
  <tr>
    <td>1</td>
  </tr>
  <tr>
    <td>2</td>
  </tr>
  <tr>
    <td>3</td>
  </tr>
  <tr>
    <td>4</td>
  </tr>
</table>
<script type="text/javascript">
    $(document).ready(function() {
        debugger;
        var tds = $("#myTable tr td"); // gets all td elements in the table with id myTable
        var col1 = $("<tr></tr>"); // holds our first row columns
        var col2 = $("<tr></tr>"); // holds our second row columns
        var halfway = Math.ceil(tds.length / 2);
        // add the first half of our td to the first row, the second half to the second
        for (var i = 0; i < tds.length; i++) {
            if (i < halfway)
                col1.append(tds[i]);
            else
                col2.append(tds[i]);
        }
        // clear out the clutter from the table
        $("#myTable").children().remove();
        // add our two rows
        $("#myTable").append(col1);
        $("#myTable").append(col2);
    });
</script>
</body>
</html>

, , , , , " ". , . for,

+2

, , , - :

$('#myTable tr').each(function() {
    $('<td/>').append( 
      $(this).find('td input') 
    ).appendTo(this);
  });
+1

Source: https://habr.com/ru/post/1699107/


All Articles