Html css сортировка таблицы

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

Узнать, как создать сортированную таблицу 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 Канада
Читайте также:  Иконки социальных сетей html

Пример

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

.

Имя Страна

Источник

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

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

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

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

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

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

 


























.

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
Просмотров: 73170
Правила перепечатки

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

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

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

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

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

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

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

Источник

Making HTML tables sortable without backend shenanigans

We’ve all wanted to do it – to just have a table sortable on the front end. You click on the column and the table sorts to that column.

We don’t want to write heaps of code on the back end that when you click on a column you have to adjust your queryset.

Here is the simplest way I’ve found so far to enable a table to be sorted by columns using JavaScript:

Introducing Sortable

Now there are two files there that you need to include:

In my Django repo they look something like this:

And I striped down the CSS and put it into my Project.css file:

/* ==================== Sortable */ .sortable th:hover::after < color: inherit; font-size: 1.2em; content: '\00a0\025B8'; >.sortable th::after < font-size: 1.2em; color: transparent; content: '\00a0\025B8'; >.sortable th.dir-d::after < color: inherit; content: '\00a0\025BE'; >.sortable th.dir-u::after < color: inherit; content: '\00a0\025B4'; >th.no-sort < pointer-events: none; >th.no-sort::after < content: none; >/* ==================== End Sortable */

Now you just add the sortable class to your table like so (for an example I assume you have context variable called users):

So what’s the catch?

Well the only catch I could find was that you HAVE to have and tags for it to work.

What about dates?

Sometime you want to sort by a value that is not the displayed value in the table. Dates are an example – we display them dd mmm yyyy but we want to sort them yyyymmdd

Sortable allows you to add the “data-sort” attribute to your table like so:

Example

Conclusion

I found getting sortable where I wanted it with CSS styling and that gotcha about took a bit of time.

But now it’s in my repo – I just put the sortable class to my table and it’s immediately sortable!

I love it – my users love it – and I’m sure you’ll love it!

7 thoughts on “Making HTML tables sortable without backend shenanigans”

Hi Andy!
The sortable works really well and very easy to use, saved my life!
I just notice it also changes the colours of the table (gray). It looks good but it is a bit off from the rest of my web. Is it possible to keep the colours as they are somehow?

I commented out the following in the sortable.css file and it works like a charm 🙂 /* .sortable <
–stripe-color: #e4e4e4;
–th-color: #fff;
–th-bg: #808080;
–td-color: #000;
–td-on-stripe-color: #000;
border-spacing: 0;
> */
/* .sortable tbody tr:nth-child(odd) <
background-color: var(–stripe-color);
color: var(–td-on-stripe-color);
> */
/* .sortable th <
background: var(–th-bg);
color: var(–th-color);
font-weight: normal;
text-align: left;
text-transform: capitalize;
vertical-align: baseline;
white-space: nowrap;
> */
/* .sortable td <
color: var(–td-color);
> */ Thanks so much Andy for this, I wouldn’t have been able to have this functionality if I had to write it myself… to newbie for that haha

Источник

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

0 for sorting by names, 1 for sorting by country: —>

.

Name Country

Источник

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