javascript - 提交时验证表单时出现问题?

标签 javascript jquery

我的代码有问题。它无法正常工作。当您开始填写表格时,请填写您的姓名,然后填写电话。如果您用鼠标单击,则表单不会提交,直到您在单击“提交”按钮之前单击其他位置或单击两次“提交”按钮或按 ENTER 键。为什么会出现这种情况?

我希望在填写最后一个字段后我可以单击鼠标提交并且它将起作用。

//validation name
    document.myform.name.onchange= function() {
        var name = document.myform.name.value;
        if (name === "") {
            document.myform.name.removeAttribute("class", "ready");
            document.myform.name.style.border = "1px solid #da3637";
            document.getElementById("Error").style.display = "block";
            document.getElementById("ErrorTwo").style.display = "none";
        } else {
                document.myform.name.style.border = "1px solid #509d12";
                document.getElementById("Error").style.display = "none";
                var pattern = new RegExp("^[а-я]+$", "i");
                var isValid = this.value.search(pattern) >= 0;
                if (!(isValid)) {
                    document.myform.name.style.border = "1px solid #da3637";
                    document.getElementById("ErrorTwo").style.display = "block";
                    document.myform.name.removeAttribute("class", "ready");
                } else {
                    document.getElementById("ErrorTwo").style.display = "none";
                    document.myform.name.style.border = "1px solid #509d12";
                    document.myform.name.setAttribute("class", "ready");
                }
        }
    };


    //validation phone
    document.myform.phone.onchange = function() {
        var name = document.myform.phone.value;
        if (name === "") {
            document.myform.phone.removeAttribute("class", "ready");
            document.myform.phone.style.border = "1px solid #da3637";
            document.getElementById("telError").style.display = "block";
            document.getElementById("telErrorTwo").style.display = "none";
        } else {
                document.myform.phone.style.border = "1px solid #509d12";
                document.getElementById("telError").style.display = "none";
                var pattern = new RegExp("[- +()0-9]+");
                var isValid = this.value.search(pattern) >= 0;

                if (!(isValid)) {
                    document.myform.phone.style.border = "1px solid #da3637";
                    document.getElementById("telErrorTwo").style.display = "block";
                } else {
                    document.getElementById("telErrorTwo").style.display = "none";
                    document.myform.phone.style.border = "1px solid #509d12";
                    document.myform.phone.setAttribute("class", "ready");
                }
            }
    };

    //filling the form
    document.myform.onchange = function() {
        var a = document.myform.name.getAttribute("class");
        var c = document.myform.phone.getAttribute("class");
        if (a === "ready" && c === "ready") {
            document.getElementById("save").removeAttribute("disabled");
            document.getElementById("save").style.cursor = "pointer";
            document.getElementById("save").style.opacity = "1";
        }
    };

    $(".callback-submit").click(function() {

    var url = "send.php"; 

    $.ajax({
           type: "POST",
           url: url,
           data: $("#callForm form").serialize(), 
           success: function(data)
           {
               var name = $("input[name=name]").val("");
               var rel= $("input[name=phone]").val("");
               $("#flipTwo").addClass("animateTwo");
           }
         });

    return false; // avoid to execute the actual submit of the form.
    });

html:

<div class="callback-form" id="callForm">
            <form name='myform'>
                <span class="close-btn" id="close">&#10006;</span>
                <p>Введите свои контактные данные</p>
                <p>Мы Вам перезвоним</p>
                <input type="text" name="name" placeholder="Имя" maxlength="30">
                <p class="Error" id="Error">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="ErrorTwo">Некорректный ввод</p>
                <input type="tel" name="phone" placeholder="Телефон" maxlength="20" minlength="7">
                <p class="Error" id="telError">Это поле обязательное для заполнения</p>
                <p class="ErrorTwo" id="telErrorTwo">Некорректный ввод</p>
                <div id="flipTwo">
                    <input class="callback-submit" type="submit" value="Отправить заявку"  name="save" id="save" disabled>
                    <span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
                </div>
                <p>Данные не передаються третьим лицам</p>
            </form>
        </div>

最佳答案

我认为你可以以更有条理的方式做到这一点,首先对你的 html 代码进行一些清理

喜欢:`

Введите свои контактные данные

Мы Вам перезвоним

Это поле обязательное для заполнения

Некорректный ввод

Это поле обязательное для заполнения

Некорректный ввод

    <div class="group">
        <div id="flipTwo">
            <input class="callback-submit" type="submit" value="Отправить subtmi"  name="save" id="save">
            <span id="iconCheckTwo">Отправлено<i class="fa fa-check" aria-hidden="true"></i></span>
        </div>
    </div>

    <p>Данные не передаються третьим лицам</p>
</form>`

然后为您的 jQuery 编写干净的代码并结构化。我完成了部分,希望你能完成剩下的:

 jQuery(document).ready(function($) {

    $('#myform').on('submit', function(){
        var form = this;
        if(validateForm(form)) {
            var values = $(form).serialize();
            var url = "send.php";
            $.ajax({
                url: url,
                type: "post",
                data: values ,
                success: function (data) {
                    var name = $("input[name=name]").val("");
                    var rel= $("input[name=phone]").val("");
                    $("#flipTwo").addClass("animateTwo");
                },
                error: function(jqXHR, textStatus, errorThrown) {
                    console.log(textStatus, errorThrown);
                }


            });
            event.preventDefault(); //changed to allow the tag manager to notice that the form was submitted
        }
        else{
            event.preventDefault();
            return false;
        }
    });

    // validate Form
    function validateForm(form) {
        valid = true;

        $(form).find('input[type=text], input[type=email]').each(function(i, val){
            if(validateField(val, true) == false) { valid = false; }
        });

        return valid;
    }

    // validate all form fields
    function validateField(field, submit) {
        var val = $(field).val();
        if(submit){

            // you can more specific
            if($(field).attr('name') == 'name' && val == '') {
                $(field).parent().find('#Error').show();
                $(field).parent().find('#ErrorTwo').hide();
                return false; }
            else if (!isValidName(val)){
                // your next rule
                return false;
            }
            // same way for email
            if($(field).attr('type') == 'email') {
                $(field).parent().addClass('error');
                return false; }
            else if (!isValidName(val)){
                // your next rule
                return false;
            }
        }
    }
    function isValidName(name) {
        var pattern = new RegExp(/^[а-я]+$/);
        return pattern.test(no);
    }
    function isValidPhone(no) {
        var pattern = new RegExp(/[- +()0-9]+/);
        return pattern.test(no);
    }
    // Run validation before Submit the form
    $('input[type=text], input[type=email]').on('change', function(){
        if($(this).val() != ''){
            $(this).parent().removeClass('error valid');
            validateField(this, false);
        }
    });
});

JSfiddle:https://jsfiddle.net/n32c2dwo/4/

关于javascript - 提交时验证表单时出现问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38762039/

相关文章:

javascript - 有什么地方 defaultChecked 比仅仅引用 checked 更有优势吗?

javascript - 无法重复点击对方

javascript - Switch 语句,它不适用于提示

php - 从表单中删除空输入元素

javascript - Office Addin - 如何判断是在 Web 客户端还是 native 中加载

javascript - 带触摸屏 UserAgent 的笔记本电脑

javascript - jQuery .text 不工作

php - Jquery 不允许我保存我的全文。只有 1 个字

javascript - 如何从 JavaScript 获取 "comment out"CSS 代码?

java - 固定侧边栏滚动