middlelady
middlelady

Reputation: 583

Bootstrap validator scroll to the first error if empty field

I'm creating a form using bootstrap with validator.js. The form is working fine but I'd like to scroll to the first error if there is some. I'm a newbie with jquery/js and I don't really now how to do for reaching this goal.

I've tried something like this:

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!
  }
})

Of course it's not working. Thank you in advance for your time and help.

Upvotes: 4

Views: 5531

Answers (1)

Nikhil Gyan
Nikhil Gyan

Reputation: 682

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

Upvotes: 6

Related Questions