找不到 html5 表单 checkValidity() 方法

新手上路,请多包涵

我正在尝试使用表单方法 checkValidity()。

http://html5test.com/ 告诉我我的浏览器 (Chrome) 支持表单级 checkValidity 方法。

但是,使用 jsfiddle http://jsfiddle.net/LcgnQ/2/ 我尝试了以下 html 和 javascript 片段:

 <form id="profileform" name="profileform">
    <input type="text" id="firstname" required>
    <input type="button" id="testbutton" value="Test">
</form>

$('#testbutton').bind('click',function(){

    try{
    alert($('#profileform').checkValidity());
    }
    catch(err){alert('err='+err)};
});

我收到一个错误: object has no method checkValidity()

我究竟做错了什么?

原文由 Journeyman 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 360
2 个回答

尝试:

 $('#profileform')[0].checkValidity()

当您选择 $('#profileform') 时,您将获得一个 jQuery 对象数组。要访问实际的 DOM 属性,您必须选择数组中的第一项,即原始 DOM 元素。

原文由 robertc 发布,翻译遵循 CC BY-SA 4.0 许可协议

只是另一种方式:

 // Fetch all the forms we want to apply custom Bootstrap validation styles to
            var forms = document.getElementsByName('profileform');
            // Loop over them and prevent submission
            var validation = Array.prototype.filter.call(forms, function (form) {
                form.addEventListener('submit', function (event) {
                    if (form.checkValidity() === false) {
                        event.preventDefault();
                        event.stopPropagation();
                    }

                }, false);
            });

原文由 Chandrapal Chetan 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题