I have a grid with data from thymeleaf attribute.
I am so neewbie in JS, trying to make it like in guide. https://www.w3schools.com/howto/howto_js_sort_table.asp But i have some troubles. First is that there is table, and i have a grid. Second one, i can`t select via JS my data. It is always undefined.
Can someone help me with some tips? Also, can i make sort on all data, or it will only sort paginated page data?
<div id="dep-grid" class="departments_table highlight">
<div class="head_departments">
<span class="head-left-grid">Name <i class="tiny material-icons arrow-sort-button">expand_more</i></span>
<span class="head-right-grid">Edit</span>
</div>
<ul>
<div class="dep-body" th:each="department : ${departmentPage.content}">
<li id="dep-li" class="left-column" th:text="${department.name}"></li>
<li class="right-column">
<div class="dep_edit">
<a id="dep-modal-pic" class="edit_dep modal-trigger" href="#modal3"
th:onclick="'javascript:showFunctionModal(\'' + ${department.id} +'\' , \'' + ${department.name} +'\');'"><i
class="material-icons">more_horiz</i></a>
</div>
</li>
</div>
</ul>
</div>
<div class="pagination pagination-dep">
<ul>
<li class="disabled"><a href="#!"><i class="material-icons">chevron_left</i></a></li>
<li><a th:if="${departmentPage.totalPages > 0}" th:each="pageNumber : ${pageNumbers}"
th:href="@{/departments(size=${departmentPage.size}, page=${pageNumber})}" th:text="${pageNumber}"
th:class="${pageNumber==departmentPage.number + 1} ? active"></a></li>
<li class="disabled"><a href="#!"><i class="material-icons">chevron_right</i></a></li>
</ul>
</div>
I need to add sort by departments name in header. Just click and it will sort asd or dsc.
Solved:
function sortDepartments() {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0, arrow;
table = document.getElementById("dep-grid");
arrow = document.getElementById('arrow-sort');
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.getElementsByClassName('dep-body');
for (i = 0; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByClassName('left-column')[0];
y = rows[i + 1].getElementsByClassName('left-column')[0];
if (dir == "asc") {
if (x.innerHTML.toLowerCase() > y.innerHTML.toLowerCase()) {
shouldSwitch = true;
arrow.innerText = 'expand_more';
break;
}
} else if (dir == "desc") {
if (x.innerHTML.toLowerCase() < y.innerHTML.toLowerCase()) {
shouldSwitch = true;
arrow.innerText = 'expand_less';
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}