개발노트/jQuery

[jQuery] 데이터 입력 팝업창 구현하기

dev-mylee 2025. 1. 6. 14:21

오늘 업무에서 데이터 입력 받는 팝업창 하나 만들었다.

이거 자주 만드는데 매번 찾아보는 것 같아서 정리해둬야겠다 😅

 

기본 구조

<div id="dataInputLayer" class="popup_layer" style="display:none;">
    <h1>데이터 입력</h1>
    <!-- 닫기 버튼은 항상 넣어주자 -->
    <a href="#" class="close"><i class="fa fa-times"></i></a>
    
    <div class="popup_content">
        <!-- 여기에 실제 내용 들어감 -->
    </div>
</div>

<!-- 까먹지 말자! dimLayer -->
<div id="dimLayer" style="display:none;"></div>

 

 

 

CSS는 늘 쓰는 거:

/* position: fixed 안하면 스크롤 할 때 팝업이 같이 움직여서 불편함 */
.popup_layer {
    position: fixed;
    top: 20%;
    left: 25%;
    width: 800px;
    z-index: 1000;  /* dimLayer보다 위에 있어야 함 */
}

/* 버튼 간격 flex로 주니까 편하다 */
.button_area {
    display: flex;
    justify-content: center;
    gap: 10px;
}

#dimLayer {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0,0,0,0.5);
    z-index: 999;
}

 

 

 

jQuery 동작부분

이거 매번 까먹어서 복붙함:

// 팝업 열 때는 꼭 이 순서로!
$('#dataInputLayer, #dimLayer').show();
$("#dataInputLayer").draggable({
    handle: "h1",  // 헤더 부분만 드래그 되게
    containment: "body",  // 화면 밖으로 안나가게
    scroll: false
});

// 닫을 때는 draggable 먼저 제거
function closePopup() {
    $('#dataInputLayer').draggable('destroy');  // 이거 빼먹으면 나중에 이상해짐
    $('#dataInputLayer, #dimLayer').hide();
    // 데이터 초기화도 잊지 말기
    $('#dataList').empty();
}

 

 

 

 

템플릿 쓸 때 실수했던 것:

// 1. 템플릿 비우고 시작하기 (안그러면 데이터 쌓임)
$('#dataList').empty();

// 2. template 오타 조심... tmpl 맞음
$("#dataListTemplate").tmpl(dataList).appendTo("#dataList");

 

 

 

입력값 검증

숫자만 입력받는 거 자주 써서 저장:

function onlyNumbers(input) {
    input.value = input.value.replace(/[^0-9]/g, '');
}

// HTML에서는 이렇게 씀
<input type="text" oninput="onlyNumbers(this);" maxlength="3"/>

 

 

 

데이터 수집할 때:

var collectedData = [];
$("#dataList tr").each(function() {
    var quantity = $(this).find("input[type='text']").val();
    // 0이나 빈값 걸러내기
    if(quantity && quantity !== "0") {
        collectedData.push({
            // 필요한 데이터 담기
        });
    }
});

// 빈 배열 체크 깜빡하지 말기
if (collectedData.length === 0) {
    alert('입력된 데이터가 없습니다.');
    return;
}

 

 

 

✅ 메모

  • dimLayer z-index 값 잘못 주면 클릭 안되는 거 한참 찾았다... 🤦‍♂️
  • draggable destroy 안하면 두 번째부터 이상하게 움직임
  • empty() 안하면 데이터가 계속 쌓여서 대참사
  • 데이터 수집할 때 빈값 체크 꼭 하자