jQuery表单验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>表单验证v1.0</title>
     <style>
        .item{
            width: 250px;
            height: 60px;
            position: relative;
        }
        .item input{
            width: 200px;
        }
        .item span{
            position: absolute;
            top: 42px;
            left: 0px;
            font-size: 8px;
            background-color: indianred;
            color: white;
            display: inline-block;
            width: 200px;
        }
    </style>

</head>
<body>
    <div>
        <form>
            <div class="item">
                用户名:<input class="c1" type="text" name="username" label="用户名"/>
                <!--<span>用户名不能为空</span>-->
            </div>
            <div class="item">
                密  码:<input  class="c1" type="password" name="pwd" label="密码"/>
                <!--<span>密码不能为空</span>-->
            </div>
            <input type="submit" value="提交" onclick="return CheckValid();" />
        </form>
    </div>
    <script src="jquery-1.12.4.js"></script>
    <script>
        function CheckValid() {
            // 找到form标签下的所有需要验证的标签
            // $('form .cl') 查找form标签下的cl类
            // $('form input[type="text"],form input[type="text"]') 查找form标签下的input标签type等于text或者password的标签

            $('form .item span').remove();
            var flag = true;

            $('form .c1').each(function () {
                // 每个元素执行一次匿名函数
                // this
                // console.log(this,$(this))
                var val = $(this).val();
                if(val.length<=0){
                    var lable = $(this).attr('label');
                    var tag = document.createElement('span');
                    tag.innerText = lable + "不能为空";
                    $(this).after(tag);  // 将添加的span标签通过after的方式添加到input的下面
                    flag = false;
                }
            });
            return flag;
        }
    </script>
</body>
</html>
表单验证(DOM事件绑定)v1.0

相关文章:

  • 2021-11-02
  • 2022-02-18
  • 2022-02-08
  • 2022-12-23
  • 2021-08-18
  • 2021-11-29
  • 2021-05-20
  • 2022-12-23
猜你喜欢
  • 2022-03-02
  • 2021-06-11
  • 2021-12-13
  • 2022-01-31
  • 2021-08-04
  • 2021-12-28
  • 2021-11-04
相关资源
相似解决方案