表单文本框光标自动移动到下一个文本框内

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jstest</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
<script type="text/javascript" src="base.js"></script>
<script type="text/javascript" src="js.js"></script>
</head>
<body>
    
    <form id="myForm" name="yourForm">
        <input type="text" name="a1" id="a1" value="" maxlength="1" />
        <input type="text" name="a1" id="a1" value="" maxlength="3" />
        <input type="text" name="a1" id="a1" value="" maxlength="5" />
        姓名:<input type="text" name="user" value="text" /><br />
        <textarea name="content" rows="" cols="" style="width: 200px;">dsfsafsdafdsafdf dsfsd</textarea>
    </form>
    
</body>
</html>
//跨浏览器添加事件
function addEvent(obj,type,fn){
    if(obj.addEventListener){
        obj.addEventListener(type,fn,false);
    }else if(obj.attachEvent){
        obj.attachEvent('on'+type,fn);
    }
}

addEvent(window,'load',function(){
    var fm = document.forms['yourForm'];
    var user = fm.elements['user'];
    var content = fm.elements['content'];
    
    addEvent(fm.elements['a1'],'keyup',tabForWard);
    addEvent(fm.elements['a2'],'keyup',tabForWard);
    addEvent(fm.elements['a3'],'keyup',tabForWard);
    
    function tabForWard(evt){
        var e = evt || window.event;
        //判断当前的长度是否和已输入的长度是否一致
        if(this.value.length == this.maxLength){
            //遍历所有控件
            for(var i = 0; i< fm.elements.length; i++){
                if(fm.elements[i] == this){
                    fm.elements[i+1].focus();
                    return;
                }
            }
        }
    }
    
});

 

posted @ 2014-09-20 15:16  little fly  阅读(831)  评论(0编辑  收藏  举报