0

所以我发现这段代码基本上阻止了表单提交,除非所有 HTML 5 表单元素都返回有效。http://jsfiddle.net/JgxU7/

var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
    forms[i].noValidate = true;

    forms[i].addEventListener('submit', function (event) {
        //Prevent submission if checkValidity on the form returns false.
        if (!event.target.checkValidity()) {
            event.preventDefault();
            //Implement you own means of displaying error messages to the user here.
        }
    }, false);
}

我现在想做的是修改它,以便检查焦点表单的有效性。它仍然应该阻止表单提交,直到它们都有效,但修改提交按钮的外观,直到它们都有效。

想知道是否有人能够提供帮助或提供任何指示?

提前致谢。

这是我想出的,我知道它写得不太好:

var forms = document.getElementsByTagName('form');
for (var i = 0; i < forms.length; i++) {
    forms[i].noValidate = true;

    forms[i].addEventListener('submit', function (event) {
        //Prevent submission if checkValidity on the form returns false.
        if (!event.target.checkValidity()) {
            event.preventDefault();
            //Implement you own means of displaying error messages to the user here.
        }
    }, false);
}


$('form').each(function (i, form) {
    var $form = $(form),
        $submit = $('[type=submit]', $form);



    $('input, textarea', $form).focus(function(event) {
        var valid = form.checkValidity();
        // change $submit here based on valid or not
        console.log(valid);
        return true;
    });
});

斯拉普

4

1 回答 1

0

一个基本的答案是这样的:在 for 循环中添加这个

(function (thisForm) {
    forms[i].addEventListener('focus', function(event) {
        //Prevent submission if checkValidity on the form returns false.
        if (!thisForm.checkValidity()) {
            // set the button to not valid
        }
        else {
            // set the button to valid
        }
        true;
    }, true);
}(forms[i]));

然而,使用 jQuery 或其他 JS 实用程序库来进行 DOM 操作和/或事件绑定很快就会更容易:因此

$('form').each(function (i, form) {
    var $form = $(form),
        $submit = $('[type=submit]', $form);

    $form.submit(function (event) {
        // Prevent submission if checkValidity on the form returns false.
        if (!event.target.checkValidity()) {
            event.preventDefault();
            //Implement you own means of displaying error messages to the user here.
        }
    }, false);

    $('input, textarea', $form).focus(function(event) {
        var valid = form.checkValidity();
        // change $submit here based on valid or not
        return true;
    });
});
于 2013-09-18T15:59:28.330 回答