码迷,mamicode.com
首页 > 其他好文 > 详细

H5阻止默认气泡,添加错误信息

时间:2018-06-23 10:06:41      阅读:192      评论:0      收藏:0      [点我收藏+]

标签:信息   title   child   ack   har   NPU   htm   pre   default   

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <title></title>
</head>
<style>
.oneline {
    line-height: 1.5;
    margin: 10px auto;
}

.oneline label {
    width: 100px;
    text-indent: 15px;
    font-size: 14px;
    font-family: "Microsoft Yahei";
    display: inline-block;
}

.oneline .sinput {
    width: 60%;
    height: 30px;
    border-radius: 6px;
    border: 1px solid #e2e2e2;
}

.oneline input[type="submit"] {
    margin-left: 20px;
    width: 80px;
    height: 30px;
    border: 0;
    background-color: #5899d0;
    color: #fff;
    font-size: 14px;
    border-radius: 6px;
}

.error-messages {
    color: red;
}
</style>

<body>
    <form id="forms">
        <div class="oneline">
            <label for="name">用户名:</label>
            <input id="name" class="sinput" name="name" type="text" required>
        </div>
        <div class="oneline">
            <label for="email">Email:</label>
            <input id="email" class="sinput" name="email" type="email" required>
        </div>
        <div class="oneline">
            <input type="submit" id="submits" value="提交">
        </div>
    </form>
    <script>
    function replaceValidationUI(form) {
        form.addEventListener("invalid", function(event) {
            event.preventDefault();
        }, true);
        form.addEventListener("submit", function(event) {
            if (!this.checkValidity()) {
                event.preventDefault();
            }
        },true);
        
        var submitBtn=document.getElementById("submits");
        submitBtn.addEventListener("click",function(){

            var invalidFields=form.querySelectorAll(":invalid"),
            errorMessages=form.querySelectorAll(".error-messages"),
            parent;

            for(var i=0;i<errorMessages.length;i++){
                errorMessages[i].parentNode.removeChild(errorMessages[i]);
            }

            for(var i=0;i<invalidFields.length;i++){
                parent=invalidFields[i].parentNode;
                parent.insertAdjacentHTML("beforeEnd","<div class=‘error-messages‘>"+invalidFields[i].validationMessage+"</div>");
            }
            if (invalidFields.length > 0) {
            invalidFields[0].focus();
            }

        })
        
        
    }
    var form = document.getElementById("forms");
    replaceValidationUI(form);
    </script>
</body>

</html>

 

H5阻止默认气泡,添加错误信息

标签:信息   title   child   ack   har   NPU   htm   pre   default   

原文地址:https://www.cnblogs.com/island1994/p/9216108.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!