Bootstrap 4:如果脚本无效,则添加“滚动到第一个无效字段”到“不提交”

时间:2018-05-13 18:49:34

标签: javascript jquery bootstrap-4

我正在使用Bootstrap 4,如果以下脚本中的任何字段无效,我将停止提交表单。 我想弄清楚(到目前为止没有成功)我需要在“ event.stopPropagation(); ”之后添加什么代码才能使表单滚动到第一个无效字段找到。 感谢您的帮助,谢谢。

形式:

<form class="needs-validation" novalidate action="search.php" id="firstform" method="post" >

如果无效则阻止提交:

  <script>
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {
        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
</script>

找到以下代码但无法找到将其嵌入“禁用表单提交”脚本或将其用作独立脚本的方法:

$("#firstform").validate({
    focusInvalid: false,
    invalidHandler: function(form, validator) {

        if (!validator.numberOfInvalids())
            return;

        $('html, body').animate({
            scrollTop: $(validator.errorList[0].element).offset().top
        }, 2000);

    }
});

3 个答案:

答案 0 :(得分:4)

您应该使用添加到元素的input.form-control:invalid伪选择器,您会看到应用于表单控件的:invalid:valid样式。

虽然使用自定义验证,但您必须查找此article可以为您提供的许多内容。

我们将使用上面的选择器document.querySelectorAll("input.form-control:invalid");获取所有错误字段列表,并滚动到表单中的第一个错误元素,以防出现多个错误。

请参阅下面的演示。

&#13;
&#13;
// Example starter JavaScript for disabling form submissions if there are invalid fields
(function() {
  'use strict';
  window.addEventListener('load', function() {
    // Fetch all the forms we want to apply custom Bootstrap validation styles to
    var forms = document.getElementsByClassName('needs-validation');
    // Loop over them and prevent submission
    var validation = Array.prototype.filter.call(forms, function(form) {
      form.addEventListener('submit', function(event) {

        if (form.checkValidity() === false) {
          event.preventDefault();
          event.stopPropagation();

          var errorElements = document.querySelectorAll(
            "input.form-control:invalid");
          errorElements.forEach(function(element) {
            element.parentNode.childNodes.forEach(function(node) {
              if (node.className == 'valid-feedback') {
                node.className = 'invalid-feedback';
                node.innerText =
                  'Please choose a Gender';
              }
            });
          });
          $('html, body').animate({
            scrollTop: $(errorElements[0]).offset().top
          }, 2000);
        }
        form.classList.add('was-validated');
      }, false);
    });
  }, false);
})();
&#13;
input[type=text],
input[type=email],
input[type=number],
textarea,
fieldset {
  /* required to properly style form 
   elements on WebKit based browsers */
  -webkit-appearance: none;
  width: 100%;
  border: 1px solid #333;
  margin: 0;
  font-family: inherit;
  font-size: 90%;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<form class="needs-validation" novalidate>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="gender">Male</label>
      <input id="gender_male" type="radio" name="gender" class="form-control col-sm-2" required>
      <label for="gender">Female</label>
      <input id="gender_female" type="radio" name="gender" class="form-control col-sm-2">
      <label for="gender">Other</label>
      <input id="gender_other" type="radio" name="gender" class="form-control col-sm-2">

      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustom01">First name</label>
      <input type="text" class="form-control" id="validationCustom01" placeholder="First name" value="Mark" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>
    <div class="col-md-4 mb-3">
      <label for="validationCustom02">Last name</label>
      <input type="text" class="form-control" id="validationCustom02" placeholder="Last name" value="Otto" required>
      <div class="valid-feedback">
        Looks good!
      </div>
    </div>

  </div>
  <div class="form-row">
    <div class="col-md-4 mb-3">
      <label for="validationCustomUsername">Username</label>
      <div class="input-group">
        <div class="input-group-prepend">
          <span class="input-group-text" id="inputGroupPrepend">@</span>
        </div>
        <input type="text" class="form-control" id="validationCustomUsername" placeholder="Username" aria-describedby="inputGroupPrepend" required>
        <div class="invalid-feedback">
          Please choose a username.
        </div>
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-6 mb-3">
      <label for="validationCustom03">City</label>
      <input type="text" class="form-control" id="validationCustom03" placeholder="City" required>
      <div class="invalid-feedback">
        Please provide a valid city.
      </div>
    </div>

  </div>
  <div class="form-row">
    <div class="col-md-3 mb-3">
      <label for="validationCustom04">State</label>
      <input type="text" class="form-control" id="validationCustom04" placeholder="State" required>
      <div class="invalid-feedback">
        Please provide a valid state.
      </div>
    </div>
    <div class="col-md-3 mb-3">
      <label for="validationCustom05">Zip</label>
      <input type="text" class="form-control" id="validationCustom05" placeholder="Zip" required>
      <div class="invalid-feedback">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <div class="form-row">
    <div class="col-md-3 mb-3">
      <label for="validationCustom05">Zip</label>
      <input type="text" class="form-control" id="validationCustom05" placeholder="Zip" required>
      <div class="invalid-feedback">
        Please provide a valid zip.
      </div>
    </div>
  </div>
  <div class="form-group">
    <div class="form-check">
      <input class="form-check-input" type="checkbox" value="" id="invalidCheck" required>
      <label class="form-check-label" for="invalidCheck">
                Agree to terms and conditions
            </label>
      <div class="invalid-feedback">
        You must agree before submitting.
      </div>
    </div>
  </div>
  <button class="btn btn-primary" type="submit">Submit form</button>
</form>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果您使用的是jQuery并且仅支持现代浏览器(如果您使用的是Bootstrap 4,则可能会出现这种情况),则可以使用以下代码来验证表单并滚动至错误的字段:

$('form#contact').submit(function(e) {
    var form = $(this);

    // HTML5 validility checker
    if (form[0].checkValidity() === false) {
        // not valid
        form.addClass('was-validated');
        $('html,body').animate({scrollTop: $('.was-validated .form-control:invalid').first().offset().top - 50},'slow');
        e.preventDefault();
        e.stopPropagation();
        return;
    }
    // valid, do something else ...
});

答案 2 :(得分:0)

尝试一下:

$( "input[type=submit]" ).click(function() {
    event.preventDefault();
    event.stopPropagation();
    //  console.log("test")
    var errorElements = document.querySelectorAll(".input-validation-error");
  for (let index = 0; index < errorElements.length; index++) {
      const element = errorElements[index];
    //  console.log(element);
      $('html, body').animate({
        scrollTop: $(errorElements[0]).focus().offset().top - 25
      }, 1000);      
      return false;
  }
});