개발노트/jQuery

[jQuery] 테이블 행 추가/삭제 + 체크박스 전체선택 기능 구현 정리

dev-mylee 2025. 1. 17. 11:02

테이블에서 행 추가/삭제하는 기능 드디어 구현 성공했다.

특히 첨부파일 여러 개 업로드하는 부분에서 행을 추가하고 체크박스로 삭제하는 기능이 필요했는데, jQuery로 해결했다.

 

1. 기본 HTML 구조:

<table>
    <thead>
        <tr>
            <th>순번</th>
            <th>
                <input type="checkbox" id="checkAll">
            </th>
            <th>내용</th>
        </tr>
    </thead>
    <tbody id="tableBody">
        <tr>
            <td>
                <span class="rowNum">1</span>
            </td>
            <td>
                <input type="checkbox" class="rowCheck">
            </td>
            <td>
                <input type="text">
            </td>
        </tr>
    </tbody>
</table>

<button id="addRowBtn">행 추가</button>
<button id="deleteRowBtn">선택 삭제</button>

 

 

 

2. jQuery로 구현한 핵심 기능들:

2-1. 행 추가 기능

function addTableRow() {
    // 최대 10개까지만 추가되도록 제한
    var currentRows = $("#tableBody tr").length;
    if (currentRows >= 10) {
        alert("최대 10개까지만 추가할 수 있습니다.");
        return;
    }
    
    var lastRow = $("#tableBody tr:last");
    var newRow = lastRow.clone();  // 마지막 행 복사
    var newSeq = currentRows + 1;

    // 새로운 행의 데이터 초기화
    newRow.find(".rowNum").text(newSeq);
    newRow.find("input[type='text']").val("");
    newRow.find(".rowCheck").prop("checked", false);

    $("#tableBody").append(newRow);
}

 

 

2-2. 행 삭제 기능

function deleteTableRows() {
    // 최소 1개 행은 남겨두기
    if ($("#tableBody tr").length === 1) {
        alert("최소 1개의 행이 필요합니다.");
        return;
    }

    // 체크된 행만 삭제
    $("#tableBody tr").each(function() {
        if ($(this).find(".rowCheck").prop("checked")) {
            $(this).remove();
        }
    });

    // 순번 다시 매기기
    $("#tableBody tr").each(function(index) {
        $(this).find(".rowNum").text(index + 1);
    });

    $("#checkAll").prop("checked", false);
}

 

 

2-3. 체크박스 전체선택 처리

// 전체선택 체크박스 클릭
$("#checkAll").on("click", function() {
    $(".rowCheck").prop("checked", $(this).prop("checked"));
});

// 개별 체크박스 클릭할 때마다 전체선택 상태 업데이트
$(document).on("click", ".rowCheck", function() {
    var total = $(".rowCheck").length;
    var checked = $(".rowCheck:checked").length;
    $("#checkAll").prop("checked", total === checked && total > 0);
});

 

 

 

3. TroubleShooting:

  1. clone()으로 행 복사할 때 이벤트도 같이 복사됨. 근데 이게 오히려 좋았음.
  2. 체크박스는 checked 속성 변경할 때 attr() 말고 prop() 써야 함. attr()은 HTML 속성을 바꾸는거고 prop()은 실제 상태를 바꾸는거라서.
  3. 동적으로 생성되는 요소에 이벤트 걸 때는 $(document).on() 방식으로 해야됨. 그냥 .on()하면 나중에 생기는 요소들한테는 이벤트가 안 걸림.
  4. 순번 매길 때 꼭 index + 1 해줘야 함. index는 0부터 시작하니까.

이거 응용해서 다음에는 여러 파일 첨부하는 기능이랑 연동해봐야겠다. 일단 행 추가/삭제하는 기본 기능은 이걸로 끝!