标签:
当用户在表单中填写完当前字段后,能否自动将焦点跳转到下一个字段以方便用户输入?
为了增强易用性,加快数据输入的速度,可以在前一个文本框中的字符达到一定的设置的字符长度后(比如电话号码,身份证号等),用户输入完后,自动将焦点切换到下一个文本框中。可以使用JS来实现这一功能。
思路:首先,比较用户输入的值和文本框中的maxlength特性,确定是否达到了指定的长度(或者允许输入的最大长度),如果这两个值相等,就去查找表单字段的集合,找到下一个文本框,将焦点切换到该文本框中。
代码:
1 <!DOCTYPE html> 2 <html> 3 <head> 4 <meta charset="UTF-8"> 5 <title>JS自动切换焦点</title> 6 <script type="text/javascript"> 7 window.onload = function(){ 8 var EventUtil = { 9 addhandler:function(element,type,handler){ 10 if(element.addEventListenter){ 11 element.addEventListenter(type,handler,false); 12 }else if(element.attachEvent){ 13 element.attachEvent("on"+type,handler); 14 }else{ 15 element["on"+type] = handler; 16 } 17 }, 18 getEvent: function(event){ 19 return event ? event: window.event; 20 }, 21 getTarget: function(){ 22 return event.target || event.srcElement; 23 }, 24 preventDefault: function(){ 25 if(event.preventDefault){ 26 event.preventDefault(); 27 }else{ 28 event.returnValue = false; 29 } 30 }, 31 stopPropagation: function(){ 32 if(event.stopPropagation){ 33 event.stopPropagation(); 34 }else{ 35 event.cancelBuddle = true; 36 } 37 }, 38 removehandler: function(element,type,handler){ 39 if(element.removeEventListenter){ 40 element.addEventListenter(type,handler,false); 41 }else if(element.detachEvent){ 42 element.detachEvent("on"+type,handler); 43 }else{ 44 element["on" +type] = null; 45 } 46 }, 47 getCharCode:function(event){ 48 if(typeof event.charCode == "number"){ 49 return event.charCode; 50 }else{ 51 return event.keyCode; 52 } 53 }, 54 } 55 56 var textarea = document.forms[0].elements["text"]; 57 var button = document.getElementById("button"); 58 59 (function(){ 60 function tabForward(event){ 61 event = EventUtil.getEvent(event); 62 var target = EventUtil.getTarget(event); 63 64 if(target.value.length == target.maxLength) { 65 var form = target.parentElement; 66 67 for(var i=0, len=form.elements.length; i<len-1; i++) 68 { 69 if(form.elements[i] == target){ 70 form.elements[i+1].focus(); 71 return; 72 } 73 } 74 } 75 } 76 var textName = document.getElementById("textName"); 77 var textTel = document.getElementById("textTel"); 78 var textID = document.getElementById("textID"); 79 80 EventUtil.addhandler(textName,"keyup",tabForward); 81 EventUtil.addhandler(textTel,"keyup",tabForward); 82 EventUtil.addhandler(textID,"keyup",tabForward); 83 })(); 84 } 85 </script> 86 </head> 87 88 <body> 89 <form> 90 <input type="text" name="Name" id="textName" maxlength="5" placeholder="您的姓名"/> 91 <input type="text" name="Tel" id="textTel" maxlength="11" placeholder="您的电话号码"/> 92 <input type="text" name="ID" id="textID" maxlength="5" placeholder="您的ID"/> 93 94 </form> 95 </body> 96 </html>
标签:
原文地址:http://www.cnblogs.com/guihailiuli/p/4375563.html