File: /var/www/html/wp-content/themes/ormedia/qrpatrol/populateTable.js
// Initially populate the table
populateTable(data);
// Listen for a click on a sort button
$('.sort').on('click', function() {
// Get the key based on the value of the button
var key = $(this).html();
// Sort the data and update our data
data = sortBy(data, key);
// Fill the table with our data
populateTable(data);
});
// Modified from: https://www.sitepoint.com/sort-array-index/
function sortBy(inputData, key) {
// Sort our data based on the given key
inputData.sort(function(a, b) {
var aVal = a[key],
bVal = b[key];
if (aVal == bVal) return 0;
return aVal > bVal ? 1 : -1;
});
return inputData;
}
// Modified from: https://stackoverflow.com/questions/5361810/fast-way-to-dynamically-fill-table-with-data-from-json-in-javascript
function populateTable(inputData) {
var keys = new Array(),
i = -1;
// Create an array of keys
$.each(inputData[0], function(key, value) {
keys[++i] = key;
});
var r = new Array(),
j = -1;
// Populate the table headers
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<th>' + keys[key] + '</th>';
});
r[++j] = '</tr>';
for (var index = 0, size = inputData.length; index < size; index++) {
// Populate the table values
r[++j] = '<tr>';
$.each(keys, function(key, value) {
r[++j] = '<td>' + inputData[index][value] + '</td>';
});
r[++j] = '</tr>';
}
// Join everything together
$('#data-table').html(r.join(''));
}