我有一个表单,其中包含需要验证的隐藏字段和display: none字段。我使用的是formvalidation.io虽然验证设置可以工作,但第一个无效字段不能自动聚焦到(页面停留在原地,不会滚动到无效元素)。
我猜这是因为它使用了animate({ scrolltop: y}),并且不能滚动到隐藏元素。
有没有办法自定义自动聚焦目标,让窗体滚动到form-group而不是隐藏字段?
发布于 2018-01-18 11:33:13
相反,我捕获了err.form.fv事件,获取了第一个违规字段,获取了它的表单组(可见)并滚动到该表单组。如下所示:
$('#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');
}
});发布于 2019-07-11 23:02:34
这是一个使用较新版本的解决方案,它使用一个名为core.form.invalid的事件来触发滚动。和getFields()来获取所有字段,并检查父级中的has-error。
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);
}
});
});我把你自己的答案当做了地下室。所以,谢谢你的帮助!希望这能帮助到一些人。
https://stackoverflow.com/questions/48134510
复制相似问题