您现在的位置: 万盛学电脑网 >> 程序编程 >> 脚本专题 >> javascript >> 正文

js文本框中禁止非数字字符输入

作者:佚名    责任编辑:admin    更新时间:2022-06-22

 <!DOCTYPE HTML>

<html lang="en-US">
<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="style.css">
</head>
<script src="http://libs.baidu.com/jquery/1.9.0/jquery.js"></script>
<body>
    <input type="text" id="phone" value="0000">
</body>
<script type="text/javascript">
    jQuery(document).ready(function($) {
        // Stuff to do as soon as the DOM is ready;
        var phone=$('#phone');
        $(phone).on('click',function(){
            phone.val('');
        })
        $(phone).on('keyup',function(evt){
            var phoneVal=phone.val();
            phoneVal=phoneVal.replace('/[^d]+/g', ''); //替换非数字字符为空格
            phoneVal=parseInt(phoneVal,10);
            if(isNaN(phoneVal)){
                phoneVal = '';
            }
            this.value=phoneVal;
        })
    });
</script>
</html>