我正在使用Bootstrap和Validator.js创建一个表单。表单工作正常,但是如果存在错误,我想滚动到第一个错误。我对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!
}
})
当然它不起作用。 感谢您的时间和帮助。