Here is my first display of the page(actually the data in rows and columns are generated from server code and database). Please also pay attention to the attributes of each data
<table>
<tr>
<td id="1" class="decorate">Item3</td>
<td class="decorate"><p>Description<p></td>
</tr>
<tr>
<td class="decorate">Item1</td>
<td class="decorate"><p>Description1</p><p>Description2</p></td>
</tr>
<tr>
<td id="2" class="decorate">Item2</td>
<td class="decorate"><p>Description3<p></td>
</tr>
</table>
<div id="tablediv"></div>
And here is the js code to read that data on OnLoad event and append the data into “tablediv” after they are sorted.
$(document).ready(function() {
var arr = new Array();
$('table tr').each(function() {
var $row = $(this);
var key = $row.find('td:first').html();
var value = $row.find('td:last').html();
console.log(value);
arr.push([key, value]);
});
arr.sort(function(a, b) {
var valueA, valueB;
valueA = a[0]; // sort by the first value of array
valueB = b[0];
if (valueA < valueB) {
return -1;
}
else if (valueA > valueB) {
return 1;
}
return 0;
});
var root=document.getElementById('tablediv');
var table=document.createElement('table');
var tbo=document.createElement('tbody');
var row, cell;
for(var i=0;i<arr.length;i++)
{
row=document.createElement('tr');
for(var j=0;j<2;j++)
{
cell=document.createElement('td');
cell.appendChild(document.createTextNode(arr[i][j]));
row.appendChild(cell);
}
tbo.appendChild(row);
}
table.appendChild(tbo);
root.appendChild(table);
});
However, I don’t like to put it in the tablediv but to completely replace the previous table (the previous one has no id or class for me to tell where it is in jquery code).
How can I do this ? And that I also would want to retain attributes inside previous table’s td. My array use here need more implementation…:-(
Just sort in place: http://jsfiddle.net/CrossEye/T44Nn/
This should mean that you don’t have to copy anything from table to table, just reuse the rows intact.