所以我发现这段代码基本上阻止了表单提交,除非所有 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;
});
});
斯拉普