我有一个表单,其中包含display: none
需要验证的隐藏字段和字段。我正在使用formvalidation.io虽然验证设置有效,但第一个无效字段无法自动聚焦到(页面保持原位并且不会滚动到无效元素)。
这是因为,我猜,它使用animate({ scrolltop: y})
并且不能滚动到隐藏元素。
有没有办法自定义自动对焦目标,以便我希望表单滚动到form-group
而不是隐藏字段?
我有一个表单,其中包含display: none
需要验证的隐藏字段和字段。我正在使用formvalidation.io虽然验证设置有效,但第一个无效字段无法自动聚焦到(页面保持原位并且不会滚动到无效元素)。
这是因为,我猜,它使用animate({ scrolltop: y})
并且不能滚动到隐藏元素。
有没有办法自定义自动对焦目标,以便我希望表单滚动到form-group
而不是隐藏字段?
相反,我捕获了该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');
}
});
这是一个使用较新版本的解决方案,它使用调用的事件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);
}
});
});
我用你自己的答案作为地下室。非常感谢你的帮忙!希望这会对某人有所帮助。