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

发布于 2025-01-08 18:10:57 字数 387 浏览 0 评论 0原文

我见过很多与此主题相关的问题,但我正在寻找简单的解决方案:

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

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

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

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.

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).

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

烂柯人 2025-01-15 18:10:57

您可以执行以下操作:

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

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

这是代码:

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

        if (!validator.numberOfInvalids())
            return;

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

    }
});

DEMO

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 focusInvalid by setting it to false.

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

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

来世叙缘 2025-01-15 18:10:57

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

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

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

if ($('#MYID').valid()) {
      //dosomething();
} else {
    $('html, body').animate({
         scrollTop: ($('.error').offset().top - 300)
    }, 2000);
}
不如归去 2025-01-15 18:10:57

对于使用 HTML5 验证 + Vanilla JavaScript 的任何人:

不是这个问题的直接答案,但由于这是搜索这个问题时出现的主要帖子,我想我会在这里为任何也在寻找的人发布我的解决方案!

我在我的 ReactJS 项目中使用了它,但它也应该可以在使用现代浏览器的任何普通 ES6 JavaScript 设置中工作。

function scrollToInvalid(form) {
  const invalidInputs = Array.from(form.querySelectorAll(':invalid, .is-invalid [, .custom-invalid-selector]'));    // set up so you can use any custom invalid classes you're adding to your elements, as well
  invalidInputs.sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top);                      // sort inputs by offset from top of viewport (handles issues with multi-column layouts, where the first element in the markup isn't necessarily the highest on the page)
  invalidInputs[0].scrollIntoView({ block: 'center', behavior: 'smooth' });                                         // scroll first (top) input into center of view, using smooth animation
}

function handleSubmit(e) {
  const form = e.currentTarget;

  if (form.checkValidity() === false ) {
    // form is invalid, don't submit
    e.preventDefault();
    e.stopPropagation();
    // scroll first invalid input into view
    scrollToInvalid(form);
  }
  else {
    // form is valid, handle submit...
  }
}
<form onSubmit="handleSubmit">
  ...
</form>

For Anyone Using HTML5 Validation + Vanilla JavaScript:

Not a direct answer to this question, but as this is the main post that comes up when searching for this question, I figured I'd post my solution here for anyone who's looking as well!

I'm using this in my ReactJS project, but it should work in just about any vanilla ES6 JavaScript setting using modern browsers, as well.

function scrollToInvalid(form) {
  const invalidInputs = Array.from(form.querySelectorAll(':invalid, .is-invalid [, .custom-invalid-selector]'));    // set up so you can use any custom invalid classes you're adding to your elements, as well
  invalidInputs.sort((a, b) => a.getBoundingClientRect().top - b.getBoundingClientRect().top);                      // sort inputs by offset from top of viewport (handles issues with multi-column layouts, where the first element in the markup isn't necessarily the highest on the page)
  invalidInputs[0].scrollIntoView({ block: 'center', behavior: 'smooth' });                                         // scroll first (top) input into center of view, using smooth animation
}

function handleSubmit(e) {
  const form = e.currentTarget;

  if (form.checkValidity() === false ) {
    // form is invalid, don't submit
    e.preventDefault();
    e.stopPropagation();
    // scroll first invalid input into view
    scrollToInvalid(form);
  }
  else {
    // form is valid, handle submit...
  }
}
<form onSubmit="handleSubmit">
  ...
</form>

怎会甘心 2025-01-15 18:10:57

只需将此代码添加到您的主题 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);

just add this code to your themes 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);
遮了一弯 2025-01-15 18:10:57

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

$(window).scrollTop(errorPosition)

似乎获取每个错误字段并不是很容易获取(至少对我来说)。

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

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

$(window).scrollTop(errorPosition)

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

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

微凉徒眸意 2025-01-15 18:10:57

你可以尝试下面使用纯javascript

setTimeout(function () {
            document
                .querySelector(".field-validation-error")
                .scrollIntoView({ behavior: "smooth", block: "center" });
        }, 0);

you can try the below which uses plain javascript

setTimeout(function () {
            document
                .querySelector(".field-validation-error")
                .scrollIntoView({ behavior: "smooth", block: "center" });
        }, 0);
总攻大人 2025-01-15 18:10:57

试试这个:

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

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;
  }
});
如梦亦如幻 2025-01-15 18:10:57
**Get the classname of input - get this div topoffset - move to this div**
beforeSubmit = function(){

setTimeout(scrollInput, 1000);
   
function scrollInput() {
   alert('hello');
    var list = document.getElementById("cpa-form").getElementsByClassName("has-error");
    if (list && list.length > 0) {
        var gimno = list[0].className;
        
        
        var classes = gimno.split(' ');
        
        var class2 = classes[1];
        
        console.log(class2);
        
        var topme = $('.'+ class2).offset().top;
        
        
        $('html, body').animate({scrollTop: '+='+topme+'px'}, 800);
        
    }
}
**Get the classname of input - get this div topoffset - move to this div**
beforeSubmit = function(){

setTimeout(scrollInput, 1000);
   
function scrollInput() {
   alert('hello');
    var list = document.getElementById("cpa-form").getElementsByClassName("has-error");
    if (list && list.length > 0) {
        var gimno = list[0].className;
        
        
        var classes = gimno.split(' ');
        
        var class2 = classes[1];
        
        console.log(class2);
        
        var topme = $('.'+ class2).offset().top;
        
        
        $('html, body').animate({scrollTop: '+='+topme+'px'}, 800);
        
    }
}
萌逼全场 2025-01-15 18:10:57
  $("#create-form").validate({ // Set Focus on first invalid input
    focusInvalid: false,
    invalidHandler: function() {
      $(this).find(":input.error:first").focus();
      }
  });
  $("#create-form").validate({ // Set Focus on first invalid input
    focusInvalid: false,
    invalidHandler: function() {
      $(this).find(":input.error:first").focus();
      }
  });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文