Skip to content

Instantly share code, notes, and snippets.

@kamaroly
Last active July 27, 2020 08:05
Show Gist options
  • Save kamaroly/15c3ef4262329a22fbee410764911ad4 to your computer and use it in GitHub Desktop.
Save kamaroly/15c3ef4262329a22fbee410764911ad4 to your computer and use it in GitHub Desktop.
A very simple light weight Vanilla Javascript HTML Table sorter
/**
* Sort an HTML TABLE IN DOM element
* @usage 1) add #sortable-table-input id to your input and listen to onkeyup event
Example: <input id="sortable-table-input" onkeyup="sortTable()" />
2) Add #sortable-table id to your HTML table
* @return
*/
function sortTable() {
// Declare variables
var input, filter, table, tableRow, index, rowTextValue;
input = document.getElementById("sortable-table-input");
filter = input.value.toUpperCase();
table = document.getElementById("sortable-table");
tableRow = table.getElementsByTagName("tr");
// Loop through all table rows, and hide those who don't match the search query
for (i = 0; i < tableRow.length; i++) {
// If this row exists then perform search
if (tableRow[i]) {
// Get inner text of the table first
rowTextValue = tableRow[i].textContent || tableRow[i].innerText;
// If inner text has same text as what is in input then
// filter it out
if (rowTextValue.toUpperCase().indexOf(filter) > -1) {
tableRow[i].style.display = "";
} else {
tableRow[i].style.display = "none";
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment