테이블 동적 추가 및 삭제

My Pale Blue Dot·2025년 2월 20일

JAVASCRIPT

목록 보기
19/26
post-thumbnail

📅 날짜: 2025-02-19

📚 학습 내용


🔹 5. 테이블 동적 추가 및 삭제

📌 개념 정리

사용자가 입력한 데이터를 테이블에 동적으로 추가하고, 삭제 버튼을 클릭하면 해당 행이 제거되도록 구현했다.

  • insertRow() : 새로운 행 추가
  • insertCell() : 행에 새로운 셀 추가
  • remove() : 특정 행 삭제
  • addEventListener() : 버튼 클릭 이벤트 추가

📌 코드 원본 (설명 포함)

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dynamic Table</title>
    <style>
        table { width: 100%; border-collapse: collapse; margin-top: 10px; }
        th, td { border: 1px solid black; padding: 8px; text-align: center; }
        .delete-btn { background-color: red; color: white; border: none; padding: 5px 10px; cursor: pointer; }
    </style>
</head>
<body>
    <!-- 입력 폼 -->
    <form id="dataForm">
        <input type="text" name="name" placeholder="이름 입력">
        <input type="number" name="age" placeholder="나이 입력">
        <button type="button" id="addBtn">추가</button>
    </form>

    <!-- 테이블 -->
    <table>
        <thead>
            <tr>
                <th>이름</th>
                <th>나이</th>
                <th>삭제</th>
            </tr>
        </thead>
        <tbody id="tableBody"></tbody>
    </table>

    <script>
        // ✅ 1. 요소 선택
        const formEl = document.getElementById('dataForm');  // 폼 요소
        const addBtn = document.getElementById('addBtn');  // 추가 버튼
        const tableBody = document.getElementById('tableBody');  // 테이블 본문

        // ✅ 2. 버튼 클릭 시 새 행 추가
        addBtn.addEventListener('click', () => {
            const name = formEl.name.value.trim();  // 입력된 이름 값
            const age = formEl.age.value.trim();  // 입력된 나이 값

            // 입력값이 비어 있으면 경고 메시지 출력 후 종료
            if (!name || !age) {
                alert("이름과 나이를 입력하세요!");
                return;
            }

            addRow(name, age);  // 새 행 추가 함수 호출
            formEl.name.value = '';  // 입력값 초기화
            formEl.age.value = '';
        });

        // ✅ 3. 새로운 행 추가 함수
        function addRow(name, age) {
            const row = tableBody.insertRow();  // 새로운 행 생성
            const nameCell = row.insertCell(0);  // 이름 셀 추가
            const ageCell = row.insertCell(1);  // 나이 셀 추가
            const deleteCell = row.insertCell(2);  // 삭제 버튼 셀 추가

            nameCell.textContent = name;  // 이름 값 설정
            ageCell.textContent = age;  // 나이 값 설정

            const deleteBtn = document.createElement('button');  // 삭제 버튼 생성
            deleteBtn.textContent = "삭제";
            deleteBtn.classList.add('delete-btn');  

            // ✅ 4. 삭제 버튼 클릭 시 해당 행 삭제
            deleteBtn.addEventListener('click', () => {
                row.remove();  // 해당 행 삭제
            });

            deleteCell.appendChild(deleteBtn);  // 삭제 버튼을 셀에 추가
        }
    </script>
</body>
</html>

📌 코드 실행 흐름 분석

1️⃣ 입력 폼, 버튼, 테이블 요소 선택

const formEl = document.getElementById('dataForm');  
const addBtn = document.getElementById('addBtn');  
const tableBody = document.getElementById('tableBody');  

document.getElementById()를 사용해 HTML 요소들을 가져와 변수에 저장


2️⃣ 버튼 클릭 시 이벤트 추가

addBtn.addEventListener('click', () => {
    const name = formEl.name.value.trim();
    const age = formEl.age.value.trim();
    if (!name || !age) {
        alert("이름과 나이를 입력하세요!");
        return;
    }
    addRow(name, age);
    formEl.name.value = '';
    formEl.age.value = '';
});

addEventListener('click', callback)을 사용하여 버튼 클릭 시 새 행 추가
🚀 입력값을 가져와 공백 제거 후 유효성 검사 진행


3️⃣ 새로운 행 추가 (addRow())

function addRow(name, age) {
    const row = tableBody.insertRow();  
    const nameCell = row.insertCell(0);  
    const ageCell = row.insertCell(1);  
    const deleteCell = row.insertCell(2);  
    nameCell.textContent = name;  
    ageCell.textContent = age;  

insertRow()를 사용해 새로운 행을 추가하고, 셀을 생성


4️⃣ 삭제 버튼 생성 및 삭제 기능 추가

const deleteBtn = document.createElement('button');  
deleteBtn.textContent = "삭제";  
deleteBtn.classList.add('delete-btn');  

deleteBtn.addEventListener('click', () => {
    row.remove();
});

deleteCell.appendChild(deleteBtn);

document.createElement('button')으로 삭제 버튼을 만들고,
addEventListener('click', () => row.remove())버튼 클릭 시 행 삭제 기능 추가


📌 최종 요약

학습 내용주요 개념
테이블 행 추가insertRow() 사용
새로운 셀 추가insertCell() 사용
삭제 기능remove() 사용
이벤트 리스너 추가addEventListener('click', callback) 사용
profile
Here, My Pale Blue.🌏

0개의 댓글