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

Mar*_*k.D 1 javascript jquery bootstrap-4

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

形成:

<form class="needs-validation" novalidate action="search.php" id="firstform" method="post" >
Run Code Online (Sandbox Code Playgroud)

如果无效则阻止提交:

  <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>
Run Code Online (Sandbox Code Playgroud)

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

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

        if (!validator.numberOfInvalids())
            return;

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

    }
});
Run Code Online (Sandbox Code Playgroud)

Muh*_*lam 5

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

尽管使用自定义验证,但您必须寻找很多article可以掩盖的内容。

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

请参阅下面的演示。

// 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);
})();
Run Code Online (Sandbox Code Playgroud)
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;
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)