Bootstrap表单验证器:如果字段为空,则滚动到第一个错误的位置

4

我正在使用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!
  }
})

当然它不起作用。 感谢您的时间和帮助。
1个回答

6
   // 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`

谢谢你的回答!@Nikhil Gyan - middlelady

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接