前端开发必备(六)------验证是否为数字

<!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>验证是否为数字</title>
    <script>
        function check() {
            var age = document.getElementById("age");
            if (age.value == null || age.value == "") {
                alert('请输入年龄!');
                age.focus();
                return;
            }
            //javascript内置函数isNaN()接收一个字符串类型的参数,如果该参数不是数字,则isNaN()方法返回true,否则返回false
            if (isNaN(age.value)) {
                alert('年龄必须为数字!');
                age.focus();
                return;
            }
            document.getElementById("myform").submit();
        }
    </script>
</head>

<body>
    <form id="myform" action="" method="post">
        <input type="text" id="age">
        <input type="submit" value="提交" onclick="check()">
    </form>
</body>

</html>

 

全部评论

相关推荐

点赞 评论 收藏
分享
06-04 09:27
门头沟学院 Java
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务