Jquery сортировка html таблицы

Jquery sort table data

I got struck in sorting tds in table using jquery. My Demo fiddle How can I call it for any table with id in my project?

var $sort = this; var $table = $('#mytable'); var $rows = $('tbody > tr',$table); $rows.sort(function(a, b) < var keyA = $('td:eq(0)',a).text(); var keyB = $('td:eq(0)',b).text(); if($($sort).hasClass('asc')) < return (keyA > keyB) ? 1 : 0; >else < return (keyA < keyB) ? 1 : 0; >>); 

I’m not familiar with dynatable, but DataTables has a lot of extra functionality. If you’re only looking to sort a table then DataTables is overkill.

7 Answers 7

function sortTable(table, order) < var asc = order === 'asc', tbody = table.find('tbody'); tbody.find('tr').sort(function(a, b) < if (asc) < return $('td:first', a).text().localeCompare($('td:first', b).text()); >else < return $('td:first', b).text().localeCompare($('td:first', a).text()); >>).appendTo(tbody); > 

could be called on any table like this

@Chandana — That’s not my code, it’s the code from the other answer, so can’t help you there, mine works -> jsfiddle.net/adeneo/d7Kbx/2

Wouldn’t this fail if the table data is numeric? I tried this one a website and it sorted considering the numbers as a String so 111 came before 2

@Rishav — Sure, not suprisingly, something that sorts text alphabetically, will most likely fail in sorting numbers numerically! Same Same, but diffelent.

Slight modification: This ignores the first table row (if you have a header) tbody.find(‘tr:not(tr:eq(0))’).sort(function (a, b)

I think you are missing the final «reset» function to sort the table. The desc code will not work because the order must be switched.

$('.sort').click(function (e) < var $sort = this; var $table = $('#mytable'); var $rows = $('tbody >tr', $table); $rows.sort(function (a, b) < var keyA = $('td', a).text(); var keyB = $('td', b).text(); if ($($sort).hasClass('asc')) < return (keyA >keyB) ? 1 : 0; > else < return (keyA >keyB) ? 0 : 1; > >); $.each($rows, function (index, row) < $table.append(row); >); e.preventDefault(); >); 

UPDATE

More in general your function can be:

function sortTable($table,order) < var $rows = $('tbody >tr', $table); $rows.sort(function (a, b) < var keyA = $('td', a).text(); var keyB = $('td', b).text(); if (order=='asc') < return (keyA >keyB) ? 1 : 0; > else < return (keyA >keyB) ? 0 : 1; > >); $.each($rows, function (index, row) < $table.append(row); >); > sortTable($('#mytable'),'asc') 

Here’s a modified version of Table sorting with jquery that works for me as a SIMPLE INTERNAL ASCENDING ROW SORTING FUNCTION

var $tbody = $('#mytable tbody'); $tbody.find('tr').sort(function(a, b) < var tda = $(a).attr('data-order'); // target order attribute var tdb = $(b).attr('data-order'); // target order attribute // if a < b return 1 return tda >tdb ? 1 // else if a > b return -1 : tda < tdb ? -1 // else they are equal - return 0 : 0; >).appendTo($tbody);

This will done by using jquery and bootstrap with search filter just call the jquery using id. For example i used this id #example you can use this as your table id and include the jquery and datatable jquery.

Here is a modified version of the answer from Adeneo. This will sort the table based on the text in the specified column instead of only the first column. This will also look for the word «Name» in the second column and make sure that row stays on top (header row).

function SortTable(table, order, nr) < var asc = order === 'asc', tbody = table.find('tbody'); tbody.find('tr').sort(function (a, b) < if ($('td:nth-child('+ nr +')', a).text() == "Name") return $('td:nth-child('+ nr +')', a).text(); else if (asc) < return $('td:nth-child('+ nr +')', a).text().localeCompare($('td:nth-child('+ nr +')', b).text()); >else < return $('td:nth-child('+ nr +')', b).text().localeCompare($('td:nth-child('+ nr +')', a).text()); >>).appendTo(tbody);> 

Thanks mate! I have suggested a small edit to your answer which will make the choice of column dynamic 🙂

If you have more then 10 rows the function no longer works properly. This is an updated version from @irvin-dominin

 $('.js_sortme').click(function (e) < var $sort = this; var $table = $('#floorplan-table-list'); var $rows = $('tbody >tr', $table); var $type = $($sort).attr('data-type'); if ($($sort).hasClass('asc')) < $('.js_sortme', $table).removeClass('desc'); $('.js_sortme', $table).removeClass('asc'); $('.js_sortme', $table).removeClass('active'); $($sort).addClass('desc'); $($sort).addClass('active'); >else < $('.js_sortme', $table).removeClass('desc'); $('.js_sortme', $table).removeClass('asc'); $('.js_sortme', $table).removeClass('active'); $($sort).addClass('asc'); $($sort).addClass('active'); >$rows.sort(function (a, b) < var keyA = parseInt($('td.'+$type+'', a).attr('data-position')); var keyB = parseInt($('td.'+$type+'', b).attr('data-position')); if ($($sort).hasClass('asc')) < var result = keyA - keyB; if (result !== 0) < return result; >// Fetch secondary keys keyA = parseInt( $('td.'+$type+'', a).attr('data-position') ); keyB = parseInt( $('td.'+$type+'', b).attr('data-position') ); return keyA - keyB; > else < var result = keyB - keyA; if (result !== 0) < return result; >// Fetch secondary keys keyA = parseInt( $('td.'+$type+'', a).attr('data-position') ); keyB = parseInt( $('td.'+$type+'', b).attr('data-position') ); return keyB - keyA; > >); $.each($rows, function (index, row) < $table.append(row); >); e.preventDefault(); >); 

The table row will look like this, using the classname as type: making each kolom sortable on its own;

  a-value-1 b-value-3  a-value-2 b-value-2  a-value-3 b-value-1  

Источник

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

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

Здравствуйте, уважаемые читатели блога LifeExample, сегодня мы будем говорить о том, как работает jQuery сортировка таблицы, и попробуем вместе разобраться с этой насущной проблемой каждого веб программиста. Уверен, что если вы еще не сталкивались с задачей сортировки таблицы на JavaScript, то рано или поздно вам это понадобится.

Таблицы в сайтах — это очень нужный и полезный элемент представления информационных данных, и работы с ними. Кроме того, когда-то без таблиц не обходилась ни одна верстка сайта.

Сегодня с появлением различных инструментов, таких как библиотека jQuery, пользователи избалованы интерактивность HTML страниц. Например, для того, чтобы изменить свои личные данные, им не нужно ждать долгой перезагрузки страницы, и можно с легкостью, перетаскивать нужное изображение в отведенную область. И таких примеров куча, одним из примеров интерактивности как раз и является функция сортировки таблицы.

Представим, что у нас есть огромное количество сводной информации, которую мы выдали пользователю в виде HTML таблицы. К примеру, это может быть скрипт, выдающий текущий курс рубля к иностранным валютам.

PHP парсер курсов валют:

$cbr_xml = str_replace ( array ( » \n » , » \r » , » \t » ) , «» , getContentPage ( ‘http://www.cbr.ru/scripts/XML_daily.asp?date_req=’ . date ( ‘d/m/Y’ , strtotime ( «+1 day» ) ) ) ) ;

if ( preg_match_all ( ‘~(.*?)~i’ , $cbr_xml , $Valute ) ) {

$table = «

» ;
foreach ( $Valute [ 1 ] as $data ) {
$table .= « » ;
preg_match ( ‘~(.*?)~i’ , $data , $NumCode ) ;
$table .= «

» ;
preg_match ( ‘~(.*?)~i’ , $data , $CharCode ) ;
$table .= «

» ;
preg_match ( ‘~(.*?)~i’ , $data , $Nominal ) ;
$table .= «

» ;
preg_match ( ‘~(.*?)~i’ , $data , $Name ) ;
$table .= «

» ;
preg_match ( ‘~(.*?)~i’ , $data , $Value ) ;
$table .= «

» ;
$table .= «

» ;
}
$table .= «

Код Сокращение Сокращение Количество Стоимость
» . $NumCode [ 1 ] . « » . $CharCode [ 1 ] . « » . $Nominal [ 1 ] . « » . $Name [ 1 ] . « » . $Value [ 1 ] . «

» ;

function getContentPage ( $url ) {
$c = curl_init ( $url ) ;
curl_setopt ( $c , CURLOPT_RETURNTRANSFER , 1 ) ;
curl_setopt ( $c , CURLOPT_FOLLOWLOCATION , 1 ) ;
$text = curl_exec ( $c ) ;
curl_close ( $c ) ;
return $text ;
}

Скрипт получает информацию в виде XML файла, с официального сайта Центрального банк Российской Федерации, парсит ее и выводит в виде готовой неотсортированной таблицы HTML.

Не отсортированная таблица валют

Так как к теме статьи его работа не относится, я не стану описывать, что конкретно происходит в коде, но если вам интересно, спрашивайте в комментариях.

Итак, у нас имеется таблица курсов валют, из которой нам нужно сделать продвинутую сортируемую таблицу jQuery , с возможностью отбирать данные по столбцам.

Сделать сортировку HTML таблицы с помощью библиотеки jQuery очень просто, но мы пойдем еще более простым способом и обратимся к использованию специально плагина для, сортировки таблицы, под названием Tablesorter.

Подключим к вышеприведенному скрипту последнюю версию jQuery и данный плагин. А так же сразу повесим на нашу таблицу событие tablesorter.

Давайте еще установим некоторые css стили для лучшей наглядности

Выполненных операций должно быть достаточно, чтобы jQuery сортировка таблицы заработала должным образом. Попробуем проверить и запустим скрипт. Вот что должно получиться:

jQuery отсортированная таблица валют

Как видите в заголовках колонок, не только появились иконки для сортировки, но и фон строк начал чередоваться, придавая таблице удобный для работы вид.

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

Так как именно он отвечает за чередование классов строк.

На данном этапе можно успокоиться и оставить все как есть, но вскоре мы поймем, что для работы с таблицей неплохо было бы иметь систему пагинации, т.е. разбивать имеющийся набор строк таблицы на части, и переключаться между ними.

Пагинация таблицы

Как это ни странно но, и эта задача решается очень просто при использовании, очередного, плагина пагинации.

Скачайте плагин пагинации на jQuery для сортировочной таблицы:

Подключим его в коде скрипта

Добавим элементы для пайджера:

Немного изменим JavaScript:

< script type = "text/javascript" >
$ ( document ) . ready ( function ( ) {
$ ( «table» ) . tablesorter ( { widgets : [ ‘zebra’ ] } ) . tablesorterPager ( { container : $ ( «#pager» ) } ) ;;
$ ( «.pagesize :last» ) . attr ( «selected» , «selected» ) ;
} ) ;

И вот у нас уже все готово:

Пагинация для таблицы

Вот так вот, малой кровью, можно организовать сортировку таблицы по столбцам. Стоит заметить, что не каждая таблица подойдет плагину Tablesorter! Необходимо, чтобы сортировочная таблица была построена по всем HTML правилам, а именно содержала в своей конструкции теги такой структуры:

В завершении статьи «jQuery сортировка» таблицы, я бы хотел предложить вам полную версию разработанного скрипта:

Читайте также похожие статьи:

Чтобы не пропустить публикацию следующей статьи подписывайтесь на рассылку по E-mail или RSS ленту блога.

Источник

jQuery Table Sorting: Sort Data on Header Click

Hamburger menu

In this tutorial, we’ll quickly discuss table sorting with jQuery. We’ll create a few quick functions that will sort table data on header click without the use of any additional plugins or bloated code. Let’s get started!

The Table Data

Let’s put together an HTML table containing some user IDs, a first name, and a last name:

































Users
ID First Name Last Name
1 Luke Skywalker X
2 Leia Organa X
3 Anakin Skywalker X

Notice that we’ve separated our table headings from the data in the body. This is crucial to ensure that, when sorting data, the table headings don’t get sorted inadvertently. You could also do the same with the table footer by using a tfoot for separation.

The Table Sort Click Event

Now that we have our table data, let’s get right into the jQuery table sorting code.

We need to create a click event to the table headers, excluding any columns with the no-sort class:

$(document).on("click", "table thead tr th:not(.no-sort)", function() var table = $(this).parents("table"); 
var rows = $(this).parents("table").find("tbody tr").toArray().sort(TableComparer($(this).index()));
var dir = ($(this).hasClass("sort-asc")) ? "desc" : "asc";

if (dir == "desc") rows = rows.reverse();
>

for (var i = 0; i < rows.length; i++) table.append(rows[i]);
>

table.find("thead tr th").removeClass("sort-asc").removeClass("sort-desc");
$(this).removeClass("sort-asc").removeClass("sort-desc") .addClass("sort-" + dir);
>);

In this function, we first identify the table and the data rows so we don’t have to make extra calls to the DOM.

Next, we identify the sort direction. If the table heading has a class of sort-asc , then descending sort is assumed. Otherwise, we will sort our data numerically or alphabetically in ascending format.

If the sort direction is descending, then we reverse the table rows with rows.reverse() .

Next, we loop through each table row and append to the table so they’re sorted in the desired manner.

The last part does some class changes so clicking on the table heading multiple times will allow for different sorting directions. It also determines whether an up or down arrow is displayed in the table heading, illustrating the sort direction to the user.

Table Row Comparisons

The TableComparer() function call in our click event function is where the sorting magic happens. This function compares each table cell value with the surrounding values and sorts accordingly:

function TableComparer(index) return function(a, b) var val_a = TableCellValue(a, index); 
var val_b = TableCellValue(b, index);
var result = ($.isNumeric(val_a) && $.isNumeric(val_b)) ? val_a - val_b : val_a.toString().localeCompare(val_b);

return result;
>
>

And the TableCellValue() that it’s related to does exactly what it sounds like. It returns the value of the table cell:

function TableCellValue(row, index) return $(row).children("td").eq(index).text();
>

CSS Explanation

You can style the table any way you would like. But there are a few notable items to consider like displaying the sort arrow in the table heading, either up or down depending on the current sort direction of the selected column.

Here is the CSS that displays the arrows as needed:

table thead tr th:after position: absolute; 
right: 2px;
>

table thead tr th.sort-asc:after content: "\25b4";
>

table thead tr th.sort-desc:after content: "\25be";
>

The first rule adds absolute positioning for the arrow on the right side of the table heading while the remaining two rules actually display the arrow in the table heading.

The jQuery table sorting click event function that we went over above is where the sort class is determined.

Conclusion

I’ve seen many examples and plugins over the years that are extremely complicated, bloated, and even unnecessary. This example takes the idea of table sorting with jQuery and simplifies it in a way that’s easy to understand and keeps your code minimal.

You can download the full example on my GitHub. Enjoy!

Источник

Читайте также:  Css after content svg color
Оцените статью