jQuery 验证表单时,如何滚动到第一个错误而不是跳转?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9392133/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 10:45:04  来源:igfitidea点击:

When form is validated, how to SCROLL to the first error instead of jumping?

jqueryjquery-validatescrollto

提问by Heraldmonkey

I've seen many questions with variations on this theme, but I'm looking for the straightforward solution:

我已经看到很多关于这个主题的变化的问题,但我正在寻找直接的解决方案:

HTML form, jQuery validation, multiple fields are required. When the form is submitted, validation jumps to the first error and highlights it. To increase usability, I want to scroll to that first error field. But it keeps blowing up the validation entirely or throwing scrollTo errors.

HTML 表单,jQuery 验证,需要多个字段。提交表单时,验证会跳转到第一个错误并突出显示它。为了提高可用性,我想滚动到第一个错误字段。但它一直在彻底破坏验证或抛出 scrollTo 错误。

I need to use the standard validation plugin (http://docs.jquery.com/Plugins/Validation) but any scroller would be fine, tho I had been trying with scrollTo (http://flesler.blogspot.com/2007/10/jqueryscrollto.html).

我需要使用标准验证插件 (http://docs.jquery.com/Plugins/Validation) 但任何滚动器都可以,但我一直在尝试使用 scrollTo (http://flesler.blogspot.com/2007/ 10/jqueryscrollto.html)。

Sample code is at http://jsfiddle.net/DtgKQ/1/, any help is appreciated.

示例代码位于http://jsfiddle.net/DtgKQ/1/,任何帮助表示赞赏。

回答by Didier Ghys

Here's what you can do:

您可以执行以下操作:

  • By default the validate plugin focuses the first erroneous element (in case there's any). Turn off the option focusInvalidby setting it to false.

  • The callback invalidHandlerhandler is executed when the form is invalid. You get access through the second parameter validatorto the validator object and thus to the errorList array. You can then animate the scroll relatively to the first erroneous element.

  • 默认情况下,验证插件会关注第一个错误元素(以防万一)。focusInvalid通过将其设置为 来关闭该选项false

  • invalidHandler当表单无效时执行回调处理程序。您可以通过第二个参数访问validator验证器对象,从而访问 errorList 数组。然后,您可以相对于第一个错误元素为滚动设置动画。

Here's the code:

这是代码:

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

        if (!validator.numberOfInvalids())
            return;

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

    }
});

DEMO

演示

回答by Thomas

I dont like all the jQuery extentions so here is my solution to this problem:

我不喜欢所有的 jQuery 扩展,所以这里是我对这个问题的解决方案:

if ($('#MYID').valid()) {
      //dosomething();
} else {
    $('html, body').animate({
         scrollTop: ($('.error').offset().top - 300)
    }, 2000);
}

回答by user3629980

just add this code to your themes javascript:

只需将此代码添加到您的主题javascript:

(function($) {
$(document).ready(function(){
    //bmo scroll to not valid
    $(".wpcf7").on('invalid.wpcf7',function(e){
        $('html, body').animate({
                scrollTop: $(".wpcf7-not-valid").first().offset().top-30
            }, 2000);
    });

});
})(jQuery);

回答by Tx3

Maybe you could check what input failed and take it's position (top) and use jQuery's scrollTop

也许你可以检查什么输入失败并占据它的位置(顶部)并使用jQuery的 scrollTop

$(window).scrollTop(errorPosition)

It seems that getting each error field isn't very easy to get (at least for me).

似乎获取每个错误字段并不容易(至少对我而言)。

Search for errorPlacementin the Validation plugin documentation. There is an example how to get each error field.

搜索errorPlacement验证插件文档。有一个示例如何获取每个错误字段。

回答by BetoSEC

try this:

尝试这个:

$( "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;
  }
});

回答by sathyakrishnapalani

  $("#create-form").validate({ // Set Focus on first invalid input
    focusInvalid: false,
    invalidHandler: function() {
      $(this).find(":input.error:first").focus();
      }
  });