HTML5表单中未找到checkValidity()方法。

78

我正在尝试使用表单方法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()
我做错了什么?
3个回答

187

尝试:

$('#profileform')[0].checkValidity()
当你选择$('#profileform')时,你会得到一个jQuery对象数组。要访问实际的DOM属性,必须选择数组中的第一个元素,即原始的DOM元素。



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);
            });

0
@robertc 的答案非常完美。不过,我想再提供另一种使用 jQuery 的 .get([index]) 函数来实现的方法。该函数可以根据给定的索引获取 DOM 元素,如果未声明索引,则获取所有匹配的 DOM 元素。
总之,最终实现的效果是完全相同的,只是写法上稍微冗长了一些。
$('#profileform').get(0).checkValidity()

这里留下文档链接:https://api.jquery.com/get/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接