Front-end

동적 테이블 생성 및 모달 데이터 선택 기능 구현

jki09871 2025. 2. 20. 16:43

🎯 1. 프로젝트 목표

이 프로젝트는 JavaScript & jQuery를 활용하여 다음 기능을 구현합니다.

동적으로 테이블을 추가/삭제할 수 있음
각 테이블마다 개별적으로 데이터를 추가할 수 있음
모달을 이용해 데이터 선택 가능
같은 테이블에서 중복된 데이터 추가 방지
각 테이블에서 개별적인 데이터 삭제 가능


📌 2. 완성된 UI 및 기능 설명

💡 기본 화면

  • + 테이블 추가 버튼을 클릭하면 새로운 테이블이 생성됨
  • 데이터 선택 버튼을 클릭하면 모달 창이 열리고 데이터 선택 가능
  • 모달에서 선택된 데이터는 해당 테이블에 추가됨
  • 같은 테이블 내에서 중복된 데이터가 추가되지 않도록 방지
  • 삭제 버튼을 클릭하면 해당 데이터가 삭제됨

📌 결과 예시

------------------------------------
| 테이블 1                         |
------------------------------------
| 메뉴명       | 발간물명          | 삭제 |
|----------------------------------|
| 비관세장벽   | 김 수출동향(Vol.4)| [삭제] |
|----------------------------------|

💻 3. HTML 코드 (기본 구조)

아래는 테이블을 추가하고, 모달을 열어 데이터를 선택할 수 있도록 하는 HTML 구조입니다.

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <title>동적 테이블 & 모달</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }
        th, td {
            border: 1px solid #ccc;
            padding: 10px;
            text-align: center;
        }
        .btn {
            padding: 5px 10px;
            cursor: pointer;
            margin-right: 5px;
        }
        .modal {
            display: none;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            width: 400px;
            background: white;
            border: 1px solid #ccc;
            padding: 20px;
            z-index: 1000;
        }
        .modal-header {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 10px;
        }
        .modal-close {
            float: right;
            cursor: pointer;
        }
    </style>
</head>
<body>

    <button class="btn" id="addTable">+ 테이블 추가</button>

    <div id="tablesContainer"></div>

    <!-- 모달 -->
    <div class="modal" id="dataModal">
        <div class="modal-header">
            데이터 선택
            <span class="modal-close" onclick="closeModal()">X</span>
        </div>
        <table>
            <thead>
                <tr>
                    <th>선택</th>
                    <th>메뉴명</th>
                    <th>발간물명</th>
                </tr>
            </thead>
            <tbody id="modalData">
                <tr>
                    <td><input type="radio" name="modalRadio" data-menu="비관세장벽" data-publication="[vol.4] 김 수출동향(2022년 4분기)"></td>
                    <td>비관세장벽</td>
                    <td>[vol.4] 김 수출동향(2022년 4분기)</td>
                </tr>
                <tr>
                    <td><input type="radio" name="modalRadio" data-menu="수출규제" data-publication="[vol.2] 수산물 수출 트렌드"></td>
                    <td>수출규제</td>
                    <td>[vol.2] 수산물 수출 트렌드</td>
                </tr>
            </tbody>
        </table>
        <button class="btn" id="saveModal">저장</button>
    </div>

🚀 4. JavaScript 코드 (기능 구현)

이제 본격적으로 JavaScript와 jQuery를 활용하여 동적인 기능을 구현해보겠습니다!

<script>
    let tableCount = 0;
    let currentTable = null;

    // ✅ 1. 테이블 추가 기능
    $("#addTable").click(function () {
        tableCount++;
        let newTable = `
            <div class="tableWrapper" id="table_${tableCount}">
                <h3>테이블 ${tableCount}</h3>
                <button class="btn openModalBtn" data-table-id="${tableCount}">데이터 선택</button>
                <button class="btn removeTable" data-table-id="${tableCount}">- 삭제</button>
                <table>
                    <thead>
                        <tr>
                            <th>메뉴명</th>
                            <th>발간물명</th>
                            <th>삭제</th>
                        </tr>
                    </thead>
                    <tbody class="tableBody"></tbody>
                </table>
            </div>`;
        $("#tablesContainer").append(newTable);
    });

    // ✅ 2. 테이블 삭제 기능
    $(document).on("click", ".removeTable", function () {
        let tableId = $(this).data("table-id");
        $("#table_" + tableId).remove();
    });

    // ✅ 3. 모달 열기 (각 테이블의 모달 버튼)
    $(document).on("click", ".openModalBtn", function () {
        currentTable = $(this).closest(".tableWrapper").find(".tableBody");
        $("#dataModal").fadeIn();
    });

    // ✅ 4. 모달 닫기
    function closeModal() {
        $("#dataModal").fadeOut();
    }

    // ✅ 5. 모달에서 데이터 선택 후 부모 테이블에 추가
    $("#saveModal").click(function () {
        let selectedData = $("input[name='modalRadio']:checked");

        if (selectedData.length === 0) {
            alert("데이터를 선택해주세요.");
            return;
        }

        let menu = selectedData.data("menu");
        let publication = selectedData.data("publication");

        // ✅ 6. 중복 체크 (현재 테이블 안에서만)
        let isDuplicate = false;
        currentTable.find("tr").each(function () {
            let existingMenu = $(this).find(".menu").text().trim();
            let existingPublication = $(this).find(".publication").text().trim();

            if (existingMenu === menu && existingPublication === publication) {
                isDuplicate = true;
                return false; // 중복이면 루프 중단
            }
        });

        if (!isDuplicate) {
            let newRow = `<tr>
                            <td class="menu">${menu}</td>
                            <td class="publication">${publication}</td>
                            <td><button class="btn deleteRow">삭제</button></td>
                          </tr>`;
            currentTable.append(newRow);
        } else {
            alert("이미 추가된 데이터입니다.");
        }

        closeModal();
    });

    // ✅ 7. 부모 테이블에서 데이터 삭제
    $(document).on("click", ".deleteRow", function () {
        $(this).closest("tr").remove();
    });
</script>

🎉 완성!

동적 테이블 생성
모달을 통한 데이터 선택
중복 데이터 방지
데이터 삭제 가능

🚀 이제 여러분의 프로젝트에 적용해보세요! 🚀