yoda yoda - 4 days ago 7
Javascript Question

Change table-like items order

I have a set of divs table-like (with rows and cols), to display a soccer table. Now, I need to be able to order that table according to the key chosen, without refreshing the page and avoiding using ajax.

Being more specific, I need to catch the values inside each "columm" refeering to the key chosen and re-order the table.

I use jQuery, so the work should be fairly easy, just not sure how to re-order an array with the id of the team and the column in cause. The table values are all numeric by the way.

Below is an example of the markup (row):

<div class="rb">
<div class="cname">Benfica</div>
<div class="tdr bold">0</div>
<div class="tdg bold">0</div>

<div class="tdg bold">0</div>
<div class="tdg bold">0</div>
<div class="tdg bold">0</div>
<div class="tdr bold" style="margin-left: 5px;">0</div>
<div class="tdg bold">0</div>
<div class="tdg bold">0</div>

<div class="tdg bold">0</div>
<div class="tdg bold">0</div>
<div class="tdr bold" style="margin-left: 5px;">0</div>
<div class="tdg bold">0</div>
<div class="tdg bold">0</div>
<div class="tdg bold">0</div>

<div class="tdg bold">0</div>
<div class="tdg bold" style="margin-left: 5px;">0</div>
<div class="tdg bold">0</div>
<div class="tdr bold">0</div>
</div>


Any thoughts?

Answer

Say you've got an array of objects, where every object corresponds to a table row, and every object has properties corresponding to table columns.

var table = [
   { rowId: 1, teamName: 'Man U', country: 'England' },
   { rowId: 2, teamName: 'FC Barcelona', country: 'Spain' }
];

now, if you've got your data arranged like this, you can create a function where you can just say drawTable(table) and it'll create the HTML markup you want. You can then do sorting in that variable, like this:

function sortTable(table, column) {
    table.sort(function(x,y) { return x[column] > y[column]; });
    return table;
}

$('#sortByTeamName').click(function() {
   table = sortTable(table, 'teamName');
   drawTable(table);
});
Comments