반응형

비밀번호등을 받기 위해 숫자나 특정 단어 하나씩 입력하고 다음칸으로 이동하는 형태의 UI를 많이 접할 수 있습니다.

해당 포스팅에서는 하나의 Input태그마다 입력을 받으면 다음칸으로 이동하고 숫자만 받는 형태를 작성해보겠습니다.

 

단순하게 maxlength와 number값 타입을 지정하더라도 영문 'e' 또는 한글 자음 모음등이 입력되는 현상😓을 볼 수 있는데, 정규식과 사용할 수 있는 이벤트등을 활용하여 처리하였습니다.😋

 

좀 더 좋은 깔끔한 방식이 있다면 댓글 부탁드립니다!🙆‍♀️

<input type="tel" maxlength="1" min="0" max="9" onlyNumber>
$(function(){
    $(document).on("keypress keyup keydown", "input[onlyNumber]", function(e){
        console.log(e.which);
        if(/[a-z|ㄱ-ㅎ|ㅏ-ㅣ|가-힣]/g.test(this.value)){ //한글 막기
            e.preventDefault();
            this.value = "";
        }else if (e.which != 8 && e.which != 0 //영문 e막기
            && e.which < 48 || e.which > 57    //숫자키만 받기
            && e.which < 96 || e.which > 105){ //텐키 받기
            e.preventDefault();
            this.value = "";
        }else if (this.value.length >= this.maxLength){ //1자리 이상 입력되면 다음 input으로 이동시키기
            this.value = this.value.slice(0, this.maxLength);
            if($(this).next("input").length > 0){
                $(this).next().focus();
            }else{
                $(this).blur();
            }
        }
    });    
});

태그 input에 type을 tel로 한 이유는 모바일 환경에서 넘버패드로 먼저 동작하도록 하기 위해 처리하였고, input태그 내부에 onlyNumber라는 속성이 있으면 동일하게 동작하도록 처리하였습니다.

 

마지막 else if문에서 길이를 체크하고 maxlength값만큼 커지거나 같아지면 다음 input이 있는지 체크 후 자동으로 포커싱하는 스크립트입니다.

 

 

동작테스트는 아래 codePen⌨을 활용해주세요!

See the Pen Get one number by one by myhappyman (@myhappyman) on CodePen.

 

 

 

 

반응형