Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying the structure of a HTML table with jQuery

Tags:

html

jquery

jsf

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

In 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 a JSF component (called <h:selectManyCheckboxes/>), and thus, I have no control on this HTML code.

However, I want to display my list of elements in 2 columns. In others words, the HTML code of my table will be something like that:

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

How can I do that using jQuery?

Thanks in advance for your help.

ps: If you need to know, the X are in fact an input and a label, i.e.:

<td><input .../><label .../></td>
like image 691
Romain Linsolas Avatar asked Nov 06 '25 09:11

Romain Linsolas


1 Answers

Given the additional information you've provided, I think that this is what you want. It traverses the table moving the cells from every second row into the previous row...

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();
    }
}
like image 88
Prestaul Avatar answered Nov 09 '25 09:11

Prestaul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!