首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >formvalidation.io自动聚焦到隐藏目标

formvalidation.io自动聚焦到隐藏目标
EN

Stack Overflow用户
提问于 2018-01-07 13:07:11
回答 2查看 521关注 0票数 0

我有一个表单,其中包含需要验证的隐藏字段和display: none字段。我使用的是formvalidation.io虽然验证设置可以工作,但第一个无效字段不能自动聚焦到(页面停留在原地,不会滚动到无效元素)。

我猜这是因为它使用了animate({ scrolltop: y}),并且不能滚动到隐藏元素。

有没有办法自定义自动聚焦目标,让窗体滚动到form-group而不是隐藏字段?

EN

回答 2

Stack Overflow用户

发布于 2018-01-18 11:33:13

相反,我捕获了err.form.fv事件,获取了第一个违规字段,获取了它的表单组(可见)并滚动到该表单组。如下所示:

代码语言:javascript
复制
$('#formMain').formValidation({
    // your settings here   
})
.on('err.form.fv', function (e) {
    // get the INVALID'ed field 
    var invalidField = $('#formMain').data('formValidation').getInvalidFields().eq(0);

    // get the form-group of that field
    var formGroup = invalidField.parents('.form-group');

    // scroll to it
    if (typeof formGroup !== 'undefined') {
        $('html, body').animate({
            scrollTop: formGroup.offset().top
        }, 300);
    } else {
        console.log('Nothing to scroll to');
    }
});
票数 1
EN

Stack Overflow用户

发布于 2019-07-11 23:02:34

这是一个使用较新版本的解决方案,它使用一个名为core.form.invalid的事件来触发滚动。和getFields()来获取所有字段,并检查父级中的has-error

代码语言:javascript
复制
var form = $('form');
document.addEventListener('DOMContentLoaded', function() {
    formValidation = FormValidation.formValidation(
        form,
        {
            plugins: {
                autoFocus: new FormValidation.plugins.AutoFocus(),
                declarative: new FormValidation.plugins.Declarative({
                    html5Input: true
                }),
                trigger: new FormValidation.plugins.Trigger(),
                submitButton: new FormValidation.plugins.SubmitButton(),
                bootstrap3: new FormValidation.plugins.Bootstrap3()
            }
        }
    ).on('core.form.invalid', function (e) {
        // get all fields
        var fields = formValidation.getFields();
        fields = Object.keys(fields).reverse();

        // get the form-group of that field
        var formGroup;
        $(fields).each(function(index, field) {
            var formGroupCandidate = $('*[name="' + field + '"]').parents('.form-group');
            if (formGroupCandidate.hasClass('has-error')) {
                formGroup = formGroupCandidate;
            }
        });

        // scroll to it
        if (typeof formGroup !== 'undefined') {
            $('html, body').animate({
                scrollTop: formGroup.offset().top
            }, 300);
        }
    });
});

我把你自己的答案当做了地下室。所以,谢谢你的帮助!希望这能帮助到一些人。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/48134510

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档