I would like to reorder many tables in alphabetical sort according to their respective caption.
Example :
Currently, I have:
table with caption "PHP"
table with caption "Javascript"
table with caption "Android"
I would like to see:
table with caption "Android"
table with caption "Javascript"
table with caption "PHP"
I don't know how to do this.
This is my code:
$('table').each(function() {
$caption = $(this).find('>caption');
$table = $(this);
$table.sort(function (a, b) {
var $a = $(a),
$b = $(b),
aVal = $a.find(">caption").text().toLowerCase(),
bVal = $a.find(">caption").text().toLowerCase();
if (aVal < bVal) return -1;
else if (aVal > bVal) return 1;
else return 0;
});
$('#results').append($table);
});
You cannot sort the tables while you're iterating through them.
First you can get the caption for each table, then group it with its corresponding table and push it into an array. Now sort the array and display the contents.
var tables = [];
$('table').each(function() {
var caption = $(this).find('caption')[0];
tables.push({
'table' : $(this),
'caption': $(caption).text().toLowerCase()
});
});
tables.sort(function (tableA, tableB){
if (tableA.caption < tableB.caption){
return -1;
}
if (tableA.caption > tableB.caption){
return 1;
}
return 0;
});
$.each( tables, function( index, tableObject){
$('#results').append(tableObject.table);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table> <caption>Zhp</caption> </table>
<table> <caption>php</caption> </table>
<table> <caption>Javascript</caption> </table>
<div id="results"></div>