본문 바로가기
Web Programming/Script

입력창에 정해진 자릿수를 입력하면 자동으로 다음으로 이동 / maxlength 입력시 .next().focus()

by hyeon-H 2021. 6. 4.
728x90
반응형

html 부분

...
<body>
	<div style="margin:20px;"> 
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
	</div>
</html>

 

script 부분

<script>
$(document).ready(function() {
    $(".inputs").keyup(function () {
        if (this.value.length == this.maxLength) {
          $(this).next('.inputs').focus();
        }
    });
});
</script>

 

 

<script>
$(document).ready(function() {
    $(".inputs").keyup(function () {
    //    if (this.value.length == this.maxLength) {
    //       $(this).next('.inputs').focus();
    //    }
    });
});
</script>

"inputs" 클래스명을 가진 input에서 4번째 문자를 keyup(입력이 끝나는 순간) 실행된다.

 

<script>
$(document).ready(function() {
    //$(".inputs").keyup(function () {
        if (this.value.length == this.maxLength) {
           $(this).next('.inputs').focus();
        }
    // });
});
</script>

현재 입력하고 있는 input의 값의 길이가 maxlength 길이와 같다면 현재 입력하고 있는 input의 다음 input으로 focus한다.

 

전체코드

<!DOCTYPE html>
<html>
<head>
<meta charset="EUC-KR">
<title>Insert title here</title>
<script type="text/javascript" src="./jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function() {
    $(".inputs").keyup(function () {
        if (this.value.length == this.maxLength) {
          $(this).next('.inputs').focus();
        }
    });
});
</script>
</head>
<body>
	<div style="margin:20px;"> 
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
		<input type="text" class="inputs" maxlength=4>
	</div>
</html>
728x90
반응형