gpt4 book ai didi

jquery - 使用HTML5验证时如何绑定(bind)提交事件?

转载 作者:太空狗 更新时间:2023-10-29 13:11:26 26 4
gpt4 key购买 nike

使用 HTML5 验证...

在 HTML5 浏览器中,验证发生在 submit 事件之前。因此,如果表单无效,提交事件永远不会触发。

我想将一个事件挂接到表单提交中,以触发表单是否通过验证。这是一个小示例,我试图在用户提交表单时 alert()

HTML:

<!DOCTYPE html>
<html>
<head><title>Example</title></head>
<body>
<form>
<input type="text" name="foo" required title="Foo field"/>
<input type="submit"/>
</form>
</body>
</html>

JavaScript:

$(function() {
$('form').submit(function() {
alert('submit!')
});
});

交互式演示:http://jsfiddle.net/gCBbR/

我的问题是:浏览器是否提供了我可以绑定(bind)到的替代事件,该事件将在验证之前运行?

最佳答案

是的,有一个事件就是出于这个原因。该事件称为 invalid当您通过 HTML5 验证方法检查有效性时用户尝试提交 for orr checkValidity() .此事件不会在 blur 或类似事件上触发而无需调用 checkValidity() 只是因为您的 input 标记中具有 HTML 验证属性。但它确实会在表单提交之前触发。

来自 W3C:

When the checkValidity() method is invoked, if the element is a candidate for constraint validation and does not satisfy its constraints, the user agent must fire a simple event named invalid that is cancelable (but in this case has no default action) at the element and return false. Otherwise, it must only return true without doing anything else.

例如你有这个标记:

<form>
<input type="text" name="foo" required title="Foo field"/>
<input type="submit"/>
</form>

然后如果输入数据无效,你需要调用checkValidity()来触发invalid事件:

document.querySelectorAll('input')[0].addEventListener('blur', function(){
this.checkValidity();
}, false);

document.querySelectorAll('input')[0].addEventListener('invalid', function(){
console.log('invalid fired');
}, false);

看看我的例子:http://jsbin.com/eluwir/2

关于jquery - 使用HTML5验证时如何绑定(bind)提交事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7587511/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com