0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

メモ

Last updated at Posted at 2025-05-20
function filterTable() {
  const nameFilter = document.getElementById("filterName").value.toLowerCase();
  const categoryFilter = document.getElementById("filterCategory").value;

  document.querySelectorAll("tbody tr").forEach(row => {
    const name = row.cells[0].textContent.toLowerCase();
    const category = row.cells[2].textContent;

    const nameMatch = name.includes(nameFilter);
    const categoryMatch = !categoryFilter || category === categoryFilter;

    row.style.display = (nameMatch && categoryMatch) ? "" : "none";
  });
}

document.getElementById("filterName").addEventListener("input", filterTable);
document.getElementById("filterCategory").addEventListener("change", filterTable);
<script>
let currentSort = { col: -1, asc: true }; // 昇順/降順の状態

function sortTable(colIndex) {
    const table = document.getElementById("aaTable");
    const tbody = table.tBodies[0];
    const rows = Array.from(tbody.rows);

    // 昇順 / 降順 切り替え(同じ列ならトグル、別列なら昇順)
    if (currentSort.col === colIndex) {
        currentSort.asc = !currentSort.asc;
    } else {
        currentSort.col = colIndex;
        currentSort.asc = true;
    }

    rows.sort((a, b) => {
        let valA = getCellValue(a.cells[colIndex]);
        let valB = getCellValue(b.cells[colIndex]);

        // ソートの方向に応じて比較
        return currentSort.asc
            ? valA.localeCompare(valB, 'ja')
            : valB.localeCompare(valA, 'ja');
    });

    rows.forEach(row => tbody.appendChild(row));
}

// セルの中身を取得(select対応)
function getCellValue(cell) {
    const select = cell.querySelector("select");
    if (select) {
        return select.options[select.selectedIndex].text.trim();
    } else {
        return cell.textContent.trim();
    }
}
</script>
<table id="aaTable" border="1">
    <thead>
        <tr>
            <th onclick="sortTable(0)">ID</th>
            <th onclick="sortTable(1)">名前</th>
            <th onclick="sortTable(2)">日付</th>
        </tr>
    </thead>
    <tbody>
        <c:forEach var="item" items="${masterList}">
            <tr>
                <td>${item.id}</td>
                <td>${item.name}</td>
                <td>${item.date}</td>
            </tr>
        </c:forEach>
    </tbody>
</table>

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?