Tristan Conant Tristan Conant - 1 month ago 8
jQuery Question

How to change the order of rows in a dynamically created table?

If I have a dynamically created table that looks something like this:

<table id="myTable">
<tr>
<th>Day</th>
<th>Hours</th>
</tr>
<tr>
<td>Weds</td>
<td>7</td>
</tr>
<tr>
<td>Fri</td>
<td>7.5</td>
</tr>
<tr>
<td>Mon</td>
<td>8</td>
</tr>
</table>


How can I order the rows Monday - Friday? Preferably using jQuery.

Answer

This uses a weekday hash to turn three-letter day abbreviations into numbers. The rows are removed from the table, ordered, and inserted back in:

var weekHash = {'Sun':0,'Mon':1,'Tue':2,'Wed':3,'Thu':4,'Fri':5,'Sat':6};
var header = $('tr:first');
var days = $('tr').not(header);
var orderedDays = [];
for (var i = 0; i < 7; i++)
{
    days.each(function(){
        if (i == weekHash[$(this).find('td:first').html()])
        {
            orderedDays.push(this);
        }
    });
}
$('tr').not(header).remove;
for (o in orderedDays)
{
    $('table').append(orderedDays[o]);    
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="myTable">
      <tr>
        <th>Day</th><th>Hours</th>
      </tr>
      <tr>
        <td>Wed</td><td>7</td>
      </tr>   
      <tr>
        <td>Fri</td><td>7.5</td>
      </tr> 
      <tr>
        <td>Mon</td><td>8</td>
      </tr>       
    </table>

You may need to change the weekday abbreviations, though, as I noticed your table says 'Weds' rather than my 'Wed'.

Comments