javascript怎样设置文本框不能输入数字

javascript怎样设置文本框不能输入数字,第1张

javascript怎样设置文本框不能输入数字

在JavaScript中,可以利用if语句和keycode来设置文本框不能输入数字,0到9的keycode值为48到57,只要控制文本框内的keycode值不在该范围内,语法为“if(charCode>46&&charCode<58)”。

本教程 *** 作环境:windows10系统、javascript1.8.5版、Dell G3电脑。

javascript怎样设置文本框不能输入数字

数字0-9keycode的值为48-57,只要在JavaScript中设置文本框中输入keycode的值在这个范围内就就取消此行为,以此就可以实现文本框不能输入数字。

示例如下:

或者:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="text" id="test">
    <script type="text/javascript">
    window.onload=function(){
             document.getElementById('test').addEventListener('keypress',function(e){
             var charCode=e.charCode;
             if(charCode>46&&charCode<58)  /*0-9 的charcode*/
             e.preventDefault();
     });
    }
    </script>
</body>
</html>

输出结果与上述结果相同,文本框内无法输入数字。

【相关推荐:javascript学习教程

以上就是javascript怎样设置文本框不能输入数字的详细内容,

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/web/699932.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-04-23
下一篇2022-04-23

发表评论

登录后才能评论

评论列表(0条)

    保存