【问题标题】:formvalidation.io autofocus to hidden targetformvalidation.io 自动对焦到隐藏目标
【发布时间】:2018-06-16 12:00:09
【问题描述】:
我有一个表单,其中包含需要验证的隐藏字段和display: none 字段。我正在使用formvalidation.io 虽然验证设置有效,但第一个无效字段无法自动聚焦到(页面保持原位并且不会滚动到无效元素)。
这是因为,我猜,它使用animate({ scrolltop: y}) 并且它不能滚动到隐藏元素。
有没有办法自定义自动对焦目标,以便我希望表单滚动到 form-group 而不是隐藏字段?
【问题讨论】:
标签:
javascript
jquery
formvalidation-plugin
formvalidation.io
【解决方案1】:
我改为捕获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');
}
});
【解决方案2】:
这是一个使用较新版本的解决方案,它使用名为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);
}
});
});
我用你自己的答案作为地下室。非常感谢你的帮忙!
希望这会对某人有所帮助。