0

How do I get rows from a table into a variable pairwise with either javascript or jquery? After that I would like to do a simple sort on the table.

<table>
 <thead>
    <tr>
        <th rowspan="2">Visitor</th>
        <td>Scheduled In</td>
        <td>Time In</td>
    </tr>
    <tr>
        <td>Scheduled Out</td>
        <td>Time Out</td>
    </tr>
</thead>
<tbody>
    <tr>
        <th rowspan="2">Santos Angelo Borodec</th>
        <td>9am</td>
        <td>&nbsp;</td>
    </tr>
    <tr>
        <td>5pm</td>
        <td>&nbsp;</td>
    </tr>
  ...
  </tbody>
</table>

For tables with just a single row for each visitor I have this javascript that works.

$('.sort-table').click(function(e) {
    var $sort = this;
    var $table = $('#sort-table');
    var $rows = $('tbody > tr',$table);
    $rows.sort(function(a, b){
        var keyA = $('th',a).text();
        var keyB = $('th',b).text();
        if($($sort).hasClass('asc')){
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA > keyB) ? 1 : 0;
        }
    });
    $.each($rows, function(index, row){
      $table.append(row);
    });
    e.preventDefault();
});

By selecting rows like tr:nth-child(4n), tr:nth-child(4n-1) did not work for me.

Is there a straightforward way to accomplish this?

This is based on the sort code from "jQuery - sort a table after adding a row to it"

Here is my fiddle that creates a boggle board: http://jsfiddle.net/MacwT/

Community
  • 1
  • 1
JHo
  • 1,068
  • 1
  • 14
  • 29

1 Answers1

1

Try this approach to do a sort on the pair of tr.

$('.sort-table').click(function (e) {
    var $sort = this;
    var $table = $('#sort-table');

   //Find the even rows and its next one, clone and wrap them into temp table.
    var $rows = $table.find('tbody > tr:even').map(function () {
        return $(this).next().andSelf().clone().wrapAll('<table />')
    }); 
  //Give each table which contains the pair to be sorted
    $rows.sort(function (a, b) {
        var keyA = $('th', a).text();
        var keyB = $('th', b).text();
        if ($($sort).hasClass('asc')) {
            return (keyA > keyB) ? 1 : 0;
        } else {
            return (keyA > keyB) ? 1 : 0;
        }
    });

    var tbody = $('tbody', $table).empty();//empty the tbody
    $.each($rows, function (index, row) {
        $(tbody).append($(row).unwrap());//Unwrap the table and get the rows alone.
    });
    e.preventDefault();
});

Demo

PSL
  • 123,204
  • 21
  • 253
  • 243
  • 1
    Thanks! That's a good solution that does not require much modification of the original code. – JHo May 24 '13 at 23:09