我正在使用带有validator.js的bootstrap创建一个表单。表单工作正常但我想滚动到第一个错误,如果有一些。我是jquery / js的新手,我现在不知道如何实现这个目标。
我尝试过这样的事情:
HTML
<form id="repost-form" method="post" enctype="multipart/form-data" role="form">
<div class="col-sm-6 form-group">
<p><?php echo __('Your project title', 'ProjectTheme'); ?></p>
<p><input type="text" size="50" class="form-control " name="project_title" value="<?php echo (empty($_POST['project_title']) ? ($post->post_title == "draft project" ? "" : $post->post_title) : $_POST['project_title']); ?>" data-error="<?php echo __('Insert the project title','ProjectTheme'); ?>" required></p>
<div class="help-block with-errors"></div>
</div>
<input class="submit_green" type="submit" name="project_submit1" value="<?php _e("Submit", 'ProjectTheme'); ?> >>" />
</form>
的js
$('#repost-form').validator().on('project_submit1', function (e) {
if (e.isDefaultPrevented()) {
$('html, body').animate({ scrollTop: $(".with-errors:first").offset().top - 50 }, 500);
$(".with-errors:first").focus();
} else {
// everything looks good!
}
})
当然它不起作用。 提前感谢您的时间和帮助。
答案 0 :(得分:5)
// add data-toggle="validator" to your form tag
$('form[data-toggle="validator"]').on('submit', function (e) {
window.setTimeout(function () {
var errors = $('.has-error')
if (errors.length) {
$('html, body').animate({ scrollTop: errors.offset().top - 50 }, 500);
}
}, 0);
});
//`originally from : https://github.com/1000hz/bootstrap-validator/issues/52`