입력 양식 포커스 자동 설정

HSGemini·2021년 5월 24일

javascript

목록 보기
3/3
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>event</title>
    <script>
        // 이벤트를 연결 합니다.
        window.onload = function () {
            // 문서 객체를 선택 합니다.
            var input_1 = document.querySelectorAll('input')[0];
            var input_2 = document.querySelectorAll('input')[1];
            //input_1
             input_1.onkeydown = function () {
                 // 글자 개수가 여섯 개 이상일 경우
                 if(6 <= input_1.value.length) {
                     //input_2로 문서 객체로 초점을 이동한다.
                     input_2.focus();
                 }
                 
             };

             //input2
             input_2.onkeydown = function (event) {
                 // 이벤트 객체를 추출 합니다.
                 var event = event || window.event;
                 //keyCode == 8:백스페이스
                 //2번째 칸에 아무것도 안적혀 있고 그 때 백스페이스를 누르면 포커스가 1번째 칸으로 가게
                 //사용자의 입력이 '백 스페이스'이고 입력된 글자가 없는 경우 1로 포커스감
                 if ( event .keyCode == 8 && input_2.value.length == 0){
                     input_1.focus();
                 }
                 
             };
        };
    </script>
</head>
<body>
    <input type = "text" maxlength = "6" />
    <!-- 6으로 제한 -->
    <span>-</span>
    <input type = "text" maxlength = "7" />
</body>
</html>
profile
공부중

0개의 댓글