jQuery表单验证

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .error{
            color: red;
        }
    </style>
</head>

<body>

<form id="f1" action="s4.html" method="post">
    <div><input name="n1" type="text"></div>
    <div><input name="n2" type="password"></div>
    <div><input name="n3" type="text"></div>
    <div><input name="n4" type="text"></div>
    <div><input name="n5" type="text"></div>

    <input type="submit" value="提交">
</form>

<script src="jquery-3.3.1.js"></script>
<script>
    <!--当页面框架加载完毕后,自动执行-->
    $(function () {
        //当页面所有元素完全加载完毕后,执行
        $(':submit').click(function () {
        $('.error').remove();
        var flag = true;
        //找到id为f1标签下所有input标签type="text"和type="password"的所有input标签
        $('#f1').find('input[type="text"],input[type="password"]').each(function () {
            var v = $(this).val();
            if(v<=0){
                //只要未输入内容时flag就置为false,表单不提交
                flag = false;
                var tag = document.createElement('span');
                tag.className = 'error';
                tag.innerHTML = '必填';
                //在当前input标签后添加span标签
                $(this).after(tag);
            }

        })
        //返回false表单就不会提交
        return flag;
    });
    })



    // <!--找到type是submit的标签-->
    // $(':submit').click(function () {
    //     var v = $(this).prev().val();
    //     if(v.length>0){
    //         return true;
    //     }else {
    //         alert('请输入内容');
    //         return false;
    //     }
    // });
</script>

</body>
</html>
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容