- HTML table sort
- 8 Answers 8
- Multiple tables, different data types and no external libraries
- Edit (Jan 11 2023): Adding date sort support.
- How TO — Sort a Table
- Creating a Sort Function
- Example
- Sort Table by Clicking the Headers
- Example
- Создаем таблицу с функцией сортировки
- 5 последних уроков рубрики «Разное»
- Как выбрать хороший хостинг для своего сайта?
- Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг — это будущее Ваших сайтов
- Разработка веб-сайтов с помощью онлайн платформы Wrike
HTML table sort
So basically I am running a mysql query that fetches data from my database and displays it in an easy to read layout for my users.
You get the gist. And now I want to let the user sort the html table by let’s say sales person. How would I easily do that using a drop down menu?
Two basic approaches : sort server-side in your database query or use a javascript data structure that you sort browser side. Both will require much more work that is visible here.
8 Answers 8
Check if you could go with any of the below mentioned JQuery plugins. Simply awesome and provide wide range of options to work through, and less pains to integrate. 🙂
If not, you need to have a link to those table headers that calls a server-side script to invoke the sort.
I’m not sure your truely understanding my question. I want to be able to sort the data that is displayed as html when the query is run. So can I use data tables to do that still?
Click the table headers to sort the table accordingly:
Name Address Sales Person user:0001 UK Melissa user:0002 France Justin user:0003 San Francisco Judy user:0004 Canada Skipper user:0005 Christchurch Alex
Library is by Stuart Langridge, his website states that its under X11 (MIT) licence. The specific table sort script is detailed here.
The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.
- add a click handler to each table header
- the click handler notes the index of the column to be sorted
- the table is converted to an array of arrays (rows and cells)
- that array is sorted using javascript sort function
- the data from the sorted array is inserted back into the HTML table
The table should, of course, be nice HTML. Something like this.
Name Age Sioned 62 Dylan 37 . etc.
So, first adding the click handlers.
const table = document.querySelector('table'); //get the table to be sorted table.querySelectorAll('th') // get all the table header elements .forEach((element, columnNo)=> < // add a click handler for each element.addEventListener('click', event =>< sortTable(table, columnNo); //call a function which sorts the table by a given column number >) >)
This won’t work right now because the sortTable function which is called in the event handler doesn’t exist.
function sortTable(table, sortColumn)< // get the data from the table cells const tableBody = table.querySelector('tbody') const tableData = table2data(tableBody); // sort the extracted data tableData.sort((a, b)=> < if(a[sortColumn] >b[sortColumn]) < return 1; >return -1; >) // put the sorted data back into the table data2table(tableBody, tableData); >
So now we get to the meat of the problem, we need to make the functions table2data to get data out of the table, and data2table to put it back in once sorted.
// this function gets data from the rows and cells // within an html tbody element function table2data(tableBody)< const tableData = []; // create the array that'll hold the data rows tableBody.querySelectorAll('tr') .forEach(row=>< // for each table row. const rowData = []; // make an array for that row row.querySelectorAll('td') // for each cell in that row .forEach(cell=>< rowData.push(cell.innerText); // add it to the row data >) tableData.push(rowData); // add the full row to the table data >); return tableData; > // this function puts data into an html tbody element function data2table(tableBody, tableData)< tableBody.querySelectorAll('tr') // for each table row. .forEach((row, i)=>< const rowData = tableData[i]; // get the array for the row data row.querySelectorAll('td') // for each table cell . .forEach((cell, j)=>< cell.innerText = rowData[j]; // put the appropriate array element into the cell >) >); >
A couple of things that you may wish to add (or reasons why you may wish to use an off the shelf solution): An option to change the direction and type of sort i.e. you may wish to sort some columns numerically ( «10» > «2» is false because they’re strings, probably not what you want). The ability to mark a column as sorted. Some kind of data validation.
This is a perfect quick solution. -Beware the missing closing ‘]’ in sortTable fx. though 😉 — Should be if(a[sortColumn] > b[sortColumn])
To use the vernacular. OMG, it works. This is the first bit of JS code that I have EVER implemented and it worked right out of the box. What fooled me first was that hovering over the table headers did not indicate they were clickable. Thank you for the comments, I will study the code perhaps seek a modification. My one column had an anchor link and it is lost after the sort.
I added a in the and a superfluous Header1 to each header text. Reminds me that I can click and when I hover the reason is visible in the status bar.
Another approach to sort HTML table. (based on W3.JS HTML Sort)
let tid = "#usersTable"; let headers = document.querySelectorAll(tid + " th"); // Sort the table element when clicking on the table headers headers.forEach(function(element, i) < element.addEventListener("click", function() < w3.sortHTML(tid, ".item", "td:nth-child(" + (i + 1) + ")"); >); >);
Click the table headers to sort the table accordingly:
Name Address Sales Person --> Name Address Sales Person user:2911002 UK Melissa user:2201002 France Justin user:2901092 San Francisco Judy user:2801002 Canada Skipper user:2901009 Christchurch Alex
Multiple tables, different data types and no external libraries
- Add event listeners to all table headers.
- Find the table related to the clicked header and get the order icon.
- Declare an object to store the table rows( tr ) and an array of values of the selected column.
- Iterate the values and check the data type for future sorting.
- Sort values and change the table header( th ) icon.
- Replace the old tbody with the ordered html.
Edit (Jan 11 2023): Adding date sort support.
Just add an attribute called data-timestamp and pass the date timestamp to it. The code will take care of the rest.
Column 1 ↑ Column 2 ↑ Column 3 ↑ Column 4 ↑ Column 5 100 Nome do produto 22 ABCASD 22DDS 454645 99 Nome do produto 12 AACASD 22DDS 354645 300 Nome do produto 22 AcCASD 32DDS 554649 400 Nomde do produto 22 AcdCASD 3d2DDS 554645 10 Nome do produto 1 cCASD DDS 4645
Column 1 ↑ Column 2 ↑ Column 3 ↑ Column 4 ↑ Column 5 100 Nome do produto 22 ABCASD 22DDS 454645 99 Nome do produto 12 AACASD 22DDS 354645 300 Nome do produto 22 AcCASD 32DDS 554649 400 Nomde do produto 22 AcdCASD 3d2DDS 554645 10 Nome do produto 1 cCASD DDS 4645
Column 12222222222 ↑ Column 2 ↑ Column 3 ↑ Column 4 ↑ Column 5 ↑ 100 Nome 221 ABCASD D 22/12/2022 99 Nome 12 AACASD C 24/12/2022 300 Nome 222 AcCASD A 20/12/2022 400 Nome 22 AcdCASD B 18/12/2023 10 Nome 11 cCASD A 26/12/2022
How TO — Sort a Table
Click the button to sort the table alphabetically, based on customer name:
Sort
Name | Country |
---|---|
Berglunds snabbkop | Sweden |
North/South | UK |
Alfreds Futterkiste | Germany |
Koniglich Essen | Germany |
Magazzini Alimentari Riuniti | Italy |
Paris specialites | France |
Island Trading | UK |
Laughing Bacchus Winecellars | Canada |
Creating a Sort Function
Example
function sortTable() <
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById(«myTable»);
switching = true;
/* Make a loop that will continue until
no switching has been done: */
while (switching) <
// Start by saying: no switching is done:
switching = false;
rows = table.rows;
/* Loop through all table rows (except the
first, which contains table headers): */
for (i = 1; i < (rows.length - 1); i++) <
// Start by saying there should be no switching:
shouldSwitch = false;
/* Get the two elements you want to compare,
one from current row and one from the next: */
x = rows[i].getElementsByTagName(«TD»)[0];
y = rows[i + 1].getElementsByTagName(«TD»)[0];
// Check if the two rows should switch place:
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) <
// If so, mark as a switch and break the loop:
shouldSwitch = true;
break;
>
>
if (shouldSwitch) <
/* If a switch has been marked, make the switch
and mark that a switch has been done: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
>
>
>
Sort Table by Clicking the Headers
Click the headers to sort the table.
Click «Name» to sort by names, and «Country» to sort by country.
The first time you click, the sorting direction is ascending (A to Z).
Click again, and the sorting direction will be descending (Z to A):
Name | Country |
---|---|
Berglunds snabbkop | Sweden |
North/South | UK |
Alfreds Futterkiste | Germany |
Koniglich Essen | Germany |
Magazzini Alimentari Riuniti | Italy |
Paris specialites | France |
Island Trading | UK |
Laughing Bacchus Winecellars | Canada |
Example
Name | Country |
---|
Создаем таблицу с функцией сортировки
В этом уроке Вы узнаете как сделать красивую таблицу с данными с возможностью сортировки по любому столбцу.
Это довольно полезная штука, особенно когда таблицы очень большие.
Первым делом подключаем стили оформления между тегами :
Внешний вид таблицы можно легко изменить, если покопаться в стилях.
Далее создаем непосредственно саму таблицу:
Name
Phone
Email
Zip
Birthdate
Last Access
Rating
Done
Salary
Score
1
Ezekiel Hart
(627) 536-4760
tortor@est.ca
53082
12/02/1962
March 26, 2009
-7
7%
$73,229
6.9
.
Вместо многоточия должны быть ряды с информацией. Как Вы видите столбцу ID мы придали класс «nosort», таким образом мы убрали возможность сортировки для него. Всей таблице был присвоен класс «sortable».
Далее идет блок с кнопками навигации по таблице:
Entries Per Page