Zach Nicodemous Zach Nicodemous - 11 days ago 7
jQuery Question

Change the order of table rows on page load

I am trying to figure out if its possible to automatically tweak the order of several table rows when the page is loaded.

I do not need any drag and drop functionality. It should be done automatically when the page is loaded.

I have about a dynamically generated table with about 10 rows and each row has its own class:

<table>
<tbody>
<tr class="Reference">
<th>Reference</th>
<td>3302</td>
</tr>
<tr class="Manufacturer">
<th>Manufacturer</th>
<td>Cuttler-Hammer</td>
</tr>
<tr class="Model">
<th>Model</th>
<td>V48M28E45B45 KVA</td>
</tr>
<tr class="Year">
<th>Year Manufactured</th>
<td></td>
</tr>
<tr class="Tonage">
<th>Tonage</th>
<td></td>
</tr>
<tr class="Shot">
<th>Shot Size Oz</th>
<td></td>
</tr>
<tr class="Size">
<th>Shot Size Grams</th>
<td></td>
</tr>
<tr class="Spacing">
<th>Tie Bar Spacing</th>
<td></td>
</tr>
<tr class="Platen">
<th>Platen Size</th>
<td></td>
</tr>
</tbody>
</table>


I need to re-order the table to that the 2nd row is 1st, the 3rd row is 2nd, and the 1st row is 3rd.

I've been sitting here trying to figure out how to do it with jQuery or Javascript for the past 45 minutes, but I am hitting a wall.

Is it possible? If so, how?

Answer

What about something like this?

Add an id to the <tbody>. Otherwise use a CSS selector (not shown).

<table>
  <tbody id="table-body">

  </tbody>
</table>

Write some javascript that runs at window.document.ready()

<script language="javascript">
  $(window.document).ready(function () {
    var tableRows = Array(), 
      i = 0, 
      tempRow = undefined;

    //clone each row node to the local array
    $('#table-body').children().each(function cloneRowsToArray() {
        tableRows.push($(this).clone());
    });

    //re-order the array as necessary
    tempRow = tableRows[0];
    tableRows[0] = tableRows[1];
    tableRows[1] = tempRow;

    //re-write the newly arranged rows.
    $('#table-body').children().each(function replaceEachRowFromArray() {
        $(this).replaceWith(tableRows[i]);
        i += 1;
    });
  });
</script>