input text輸完自動跳到下一個


應用場景:

短信驗證碼輸入

效果:

input輸入框,輸入完以后自動跳轉到下一個

思路:



  1. 四個輸入框
  2. 進入聚焦到第一個輸入框
  3. 第一個輸入框輸完一個字符后自動聚焦到下一個輸入框
1.四個輸入框
<input type="text" name="sn1"  id="sn1"/>
<input type="text" name="sn2"  id="sn2"/>
<input type="text" name="sn3"  id="sn3"/>
<input type="text" name="sn4"  id="sn4"/>

2. 文檔加載完成后聚焦到第一個輸入框
$(function(){
	$("#sn1").focus();
})
3.用jquery獲取到這四個輸入框,遍歷四個輸入框,如果發生輸
入事件,判斷輸入框內的值。如果小於1個字符,那么前一個輸入
框獲取到焦點;如果大於或者等於一個字符,那么后一個輸入框
獲取到焦點。這樣就完成了input自動跳到下一個輸入框。
$("input[name^='sn']").each(function(){
	$(this).keyup(function(e){
		if($(this).val().length < 1){
			$(this).prev().focus();
		}else{
			if($(this).val().length >= 1){
				$(this).next().focus();
			}
		}
	});
	
});

修復

如果不限定input輸入框的長度,或出現輸入完后可再輸入的情況。

<input type="text" name="sn1" maxlength="1" id="sn1"/>
<input type="text" name="sn2" maxlength="1" id="sn2"/>
<input type="text" name="sn3" maxlength="1" id="sn3"/>
<input type="text" name="sn4" maxlength="1" id="sn4"/>

<script type="text/javascript">
	$(function(){
		$("#sn1").focus();

		//自動跳到下一個輸入框
		$("input[name^='sn']").each(function(){
			$(this).keyup(function(e){
				if($(this).val().length < 1){
					$(this).prev().focus();
				}else{
					if($(this).val().length >= 1){
						$(this).next().focus();
					}
				}
			});
			
		});
	});
</script>	

完善

<input type="text" name="sn1" maxlength="1" id="sn1"/>
<input type="text" name="sn2" maxlength="1" id="sn2"/>
<input type="text" name="sn3" maxlength="1" id="sn3"/>
<input type="text" name="sn4" maxlength="1" id="sn4"/>

<script type="text/javascript">
	$(function(){
		$("#sn1").focus();
		function device_verify(){
			console.log($("#sn1").val()+$("#sn2").val()+$("#sn3").val()+$("#sn4").val());
		}

		//自動跳到下一個輸入框
		$("input[name^='sn']").each(function(){
			$(this).keyup(function(e){
				if($(this).val().length < 1){
					$(this).prev().focus();
				}else{
					if($(this).val().length >= 1){
						$(this).next().focus();
					}
				}
			});
			
		});

		$("input[type='text'][id^='sn']").bind('keyup',
        function() {
            var len = $("#sn1").val().length + $("#sn2").val().length + $("#sn3").val().length + $("#sn4").val().length;
            if (len == 4) device_verify();
        });
	});

</script>

兼容IE的寫法

參考 input text框 輸完一個自動跳到下一個


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM