限定文本框内只能输入15位数字

想要实现限定文本框内只能输入15位的数字的效果。但是现在实现的情况是只能限定不能输入英文字母,还不能限制汉字的输入,从网上找到的资料看来,需使用正则表达式来判断。不建议使用依赖keycode的判断,因为粘贴、中文输入法、自动填表等都是不触发key事件的。

而且限定的length是15,却能输入17位数字

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>限制用户只能输入数字</title>
    <link href="../../css/main.css" rel="stylesheet" type="text/css"/>
    <link href="../../css/rawJavascript.css" rel="stylesheet" type="text/css"/>
    <script src="../../js/util.js"></script>
</head>
<body>
<div class="content-box numOnly">
    <form id="form1">
        <div class="list-item">
            <label for="numOnly">限定只能输入15位数字</label><input id="numOnly" type="text"/><span class="delete fl" title="清除" >×</span>
            <span id="info" class="info"></span>
        </div>
    </form>
</div>
<script>
    var str = '';
    window.onload = function () {
        var form1 = document.getElementById('form1');
        var numOnly = document.getElementById('numOnly');
        var delBtn = getByClass(form1,'delete');

        numOnly.onkeydown = function (ev) {
            var oEvent = ev||event;
            if(str.length<=15){
                if((oEvent.keyCode>=48)&& (oEvent.keyCode<=57)||((oEvent.keyCode>=96)&&(oEvent.keyCode<=105))||(oEvent.keyCode==8)){
                    str = numOnly.value;
                    if(str.length>0){
                        showDel(delBtn[0],numOnly);
                    }else{
                        disDel(delBtn[0]);
                    }
                }else{
                    info.innerHTML = "只能输入15位";
                    return false;
                };
            }
            else{
                return false;
            }
        };
        numOnly.onfocus = function () {
            if(str.length>0){
                showDel(delBtn[0],numOnly);
            };
        };
        
        numOnly.onblur = function () {
            disDel(delBtn[0]);
        }
    };

    function showDel(obj, functor ) {
        obj.style.display = "block";
        obj.onclick = function () {
            functor.value = "";
            str = '';
        };
    };

    function disDel(obj) {
        obj.style.display = "none";
    };
</script>
</body>
</html>

css样式

.numOnly {
    position: relative;
}
.list-item{
    position: relative;
    display: inline;
}
.list-item input{
    padding-right: 20px;
    letter-spacing: 2px;
}
.list-item .info{
    display: block;
    color: #eb4960;
}
.numOnly .delete{
    position: absolute;
    right: 1px;
    margin-top: -22px;
    padding: 0px 5px;
    cursor: pointer;
    display: none;
}
.numOnly .delete:hover{
    background: #eeeeee;
}

-------------找到正确的实现方法时会补充---2016-06-29-----------------------------------------

 

posted @ 2016-06-29 16:06  Viola_left  阅读(2023)  评论(0编辑  收藏  举报