HTML 테이블 Row 순서 이동 기능 개발 / TableDnD 사용법

TableDnD 사용법

TableDnD 라이브러리 추가

<head>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/TableDnD/0.9.1/jquery.tablednd.js" integrity="sha256-d3rtug+Hg1GZPB7Y/yTcRixO/wlI78+2m08tosoRn7A=" crossorigin="anonymous"></script>
</head>

table이 있는 HTML 헤더에 javascript TableDnD 라이브러리를 추가합니다.

HTML table 예시

<table id="table-1" class="table">
    <colgroup>
        <col width="6%">
        <col width="20%">
        <col width="9%">
        <col width="9%">
        <col width="*">
        <col width="8%">
        <col width="8%">
    </colgroup>
    <thead>
        <tr>
            <th>이동</th>
            <th>상위 분류 이름</th>
            <th>순서</th>
            <th>ID</th>
            <th>이름</th>
            <th>콘텐츠 수</th>
            <th>사용여부</th>
        </tr>
    </thead>
    <tbody id="listBody" class="listBody">
    </tbody>
</table>

TableDnD를 사용하기 위해, table에 id 부여가 필요합니다.

Table Row 추가 예시

function setCtgryTableRow(tableList) {
    // 테이블 Row 수
    document.getElementById("tableCnt").innerHTML = topicList.length;

    // 우측 테이블 목록 추가 처리
    let tableHtml = '';

    if(tableList.length > 0) {
        for (const ctgryMap of tableList) {
            tableHtml += '<tr id="ctgry_' + ctgryMap.id + '">';
            tableHtml += '<td class="dragHandle">';
            tableHtml += '<img src="../images/admin/ico_move.png" alt="">';
            tableHtml += '</td>';
            tableHtml += '<td>' + (ctgryMap.parent_name == null ? '' : ctgryMap.parent_name) + '</td>';
            tableHtml += '<td class="sort">' + ctgryMap.sort + '</td>';
            tableHtml += '<td>' + ctgryMap.id + '</td>';
            tableHtml += '<td>' + ctgryMap.name + '</td>';
            tableHtml += '<td>' + ctgryMap.content_cnt + '개</td>';
            tableHtml += '<td>' + (ctgryMap.use_yn === 'Y' ? '사용' : '미사용') + '</td>';
            tableHtml += '</tr>';
        }
    }else {
        tableHtml += '<tr>';
        tableHtml += '<td colspan="7" name="nullRow">' + '카테고리 데이터가 없습니다.' + '</td>';
        tableHtml += '</tr>';
    }

    const listBody = document.getElementById("listBody");

    listBody.innerHTML = tableHtml;

    // 테이블 새로 그려서 TableDnD 활성화 필요
    onTableDnD();
}

fetch로 DB에서 받아온 List로 테이블 Row 그리기 후 TableDnD 활성화하는 예시입니다.

TableDnD 활성화 함수 예시

function onTableDnD() {
    $("#table-1").tableDnD({
        onDragClass: "myDragClass",
        dragHandle: ".dragHandle",
        onDrop: function(table, row) {
            var rows = table.tBodies[0].rows;

            const ctgryList = new Array();

            for (var i=0; i<rows.length; i++) {

                // 테이블 내 순서 열 정렬 변경
                const sort = rows[i].getElementsByClassName("sort")[0].innerHTML = i+1;

                const id = rows[i].id;

                // 카테고리 순서 JSON List 생성
                const ctgryRow = new Object();
                ctgryRow.parent_id = document.getElementById("w_parentId").value;
                ctgryRow.id = id.substring(id.lastIndexOf("_")+1);
                ctgryRow.sort = sort;

                ctgryList.push(ctgryRow);
            }

            const errMsg = "카테고리 순서를 변경할 수 없습니다. 관리자에게 문의해주세요.";

            // 카테고리 순서 변경 처리
            fetch('/ctgry/topic/updateTopicSort', {
                method: 'POST',
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(ctgryList)
            })
            .then((response) => response.json())
            .then((data) => {
                if(data.success == true) {
                    alert("카테고리 순서가 변경되었습니다.");

                    location.reload();
                }else {
                    alert(errMsg);
                }
            })
            .catch((error) => {
                alert(errMsg);
            })
        }
    });
}

onDrop은 테이블 row의 순서 이동 아이콘이 위/아래로 드래그 앤 드롭 되면 실행할 이벤트 함수입니다.

Leave a comment