Document

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.

Читайте также:  Html фоновое изображение div

The way I have sorted HTML tables in the browser uses plain, unadorned Javascript.

  1. add a click handler to each table header
  2. the click handler notes the index of the column to be sorted
  3. the table is converted to an array of arrays (rows and cells)
  4. that array is sorted using javascript sort function
  5. the data from the sorted array is inserted back into the HTML table

The table should, of course, be nice HTML. Something like this.

  . etc.
NameAge
Sioned62
Dylan37

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

  1. Add event listeners to all table headers.
  2. Find the table related to the clicked header and get the order icon.
  3. Declare an object to store the table rows( tr ) and an array of values of the selected column.
  4. Iterate the values and check the data type for future sorting.
  5. Sort values and change the table header( th ) icon.
  6. 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

Источник

Создаем таблицу с функцией сортировки

В этом уроке Вы узнаете как сделать красивую таблицу с данными с возможностью сортировки по любому столбцу.

Это довольно полезная штука, особенно когда таблицы очень большие.

Первым делом подключаем стили оформления между тегами :

Внешний вид таблицы можно легко изменить, если покопаться в стилях.

Далее создаем непосредственно саму таблицу:

 


























.

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






Вначале идет настройка отображения количества рядов на странице (по умолчанию стоит 10, но Вы можете выбрать любое значение), далее кнопки ручного перехода со страницы на страницу и текстовая информация о странице, на которой Вы находитесь.

И в конце нам необходимо инициализировать саму функцию сортировки (можно это сделать после таблицы):


Все готово. Пользуйтесь 🙂 Всего наилучшего.

Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: www.leigeber.com
Перевел: Максим Шкурупий
Урок создан: 25 Мая 2009
Просмотров: 73182
Правила перепечатки

5 последних уроков рубрики «Разное»

Как выбрать хороший хостинг для своего сайта?

Выбрать хороший хостинг для своего сайта достаточно сложная задача. Особенно сейчас, когда на рынке услуг хостинга действует несколько сотен игроков с очень привлекательными предложениями. Хорошим вариантом является лидер рейтинга Хостинг Ниндзя — Макхост.

Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг — это будущее Ваших сайтов

Проект готов, Все проверено на локальном сервере OpenServer и можно переносить сайт на хостинг. Вот только какую компанию выбрать? Предлагаю рассмотреть хостинг fornex.com. Отличное место для твоего проекта с перспективами бурного роста.

Разработка веб-сайтов с помощью онлайн платформы Wrike

Создание вебсайта — процесс трудоёмкий, требующий слаженного взаимодействия между заказчиком и исполнителем, а также между всеми членами коллектива, вовлечёнными в проект. И в этом очень хорошее подспорье окажет онлайн платформа Wrike.

Источник

Как сделать — Сортировка таблицы

Узнать, как создать сортированную таблицу HTML с помощью JavaScript.

Нажмите кнопку, чтобы отсортировать таблицу в алфавитном порядке на основе имени клиента:

Сортировать

Имя Страна
Berglunds snabbkop Швеция
North/South Великобритания
Alfreds Futterkiste Германия
Koniglich Essen Германия
Magazzini Alimentari Riuniti Италия
Париж specialites Франция
Island Trading Великобритания
Laughing Bacchus Winecellars Канада

Создание функции сортировки

Пример

function sortTable() <
var table, rows, switching, i, x, y, shouldSwitch;
table = document.getElementById(«myTable»);
switching = true;
/* Сделайте цикл, который будет продолжаться до тех пор, пока
никакого переключения не было сделано: */
while (switching) <
// Начните с того: переключение не выполняется:
switching = false;
rows = table.rows;
/* Цикл через все строки таблицы (за исключением
во-первых, который содержит заголовки таблиц): */
for (i = 1; i < (rows.length - 1); i++) <
// Начните с того, что не должно быть никакого переключения:
shouldSwitch = false;
/* Получите два элемента, которые вы хотите сравнить,
один из текущей строки и один из следующей: */
x = rows[i].getElementsByTagName(«TD»)[0];
y = rows[i + 1].getElementsByTagName(«TD»)[0];
// Проверьте, должны ли две строки поменяться местами:
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) <
// Если это так, отметьте как переключатель и разорвать цикл:
shouldSwitch = true;
break;
>
>
if (shouldSwitch) <
/* Если переключатель был отмечен, сделайте переключатель
и отметьте, что переключатель был сделан: */
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
>
>
>

Сортировка таблицы по заголовкам

Щелкните заголовки, чтобы отсортировать таблицу.

Нажмите «Имя», чтобы отсортировать по имени «Страна», чтобы отсортировать по странам.

При первом щелчке направление сортировки будет возрастать (от A до Z).

Щелкните еще раз, и направление сортировки будет нисходящим (от Z до A):

Имя Страна
Berglunds snabbkop Швеция
North/South Великобритания
Alfreds Futterkiste Германия
Koniglich Essen Германия
Magazzini Alimentari Riuniti Италия
Париж specialites Франция
Island Trading Великобритания
Laughing Bacchus Winecellars Канада

Пример

0 для сортировки по именам, 1 для сортировки по стране: —>

.

Имя Страна

Источник

Оцените статью