javascript - 仅验证表单的可见部分

标签 javascript jquery html css

我已经尝试让它工作好几天了,但无论我读什么资源,我都只是在原地打转。我认为我的代码中会有很多错误,但我就是无法弄清楚。 我有一个表单,我想将其分解为更小的部分,单击下一个按钮时,它将验证该部分中的所有数据,然后隐藏它并显示下一部分。我还遇到了我的表格问题,根据该人是否有伴侣或 child ,在各个部分中添加了内容。我不确定如何处理这个问题,因此非常感谢一些提示。

这是我的验证函数,完整代码的jfiddle如下

$(".next").click(function() {
$('#travelform').find(":visible").find("input[required]").each(function(){
    var myPattern = $(this).attr('pattern');
    var myPlaceholder = $(this).attr('placeholder');
    var isValid = $(this).val().search(myPattern) >= 0;
    var isEmpty = true;

    var abort = false;
    $("div.error").remove();

    //traverse through each required field to ensure it's been filled in
    $(':input[required]').each(function() {
       if($(this).val()==='') {
           $(this).after('<div class="error">This is a required field</div>');
           abort = true;
       } 
    });
    if (abort) { return false;} else {return true;}
});

});

fiddle :https://jsfiddle.net/gq4kyhs3/

最佳答案

为什么不向所有已验证并具有值的输入添加一个类,然后在每次按下“next”时检查这一点,如下所示:

$(".next").click(function() {
$('#travelform').find(":visible").find("input[required]").each(function(){
    var myPattern = $(this).attr('pattern');
    var myPlaceholder = $(this).attr('placeholder');
    var isValid = $(this).val().search(myPattern) >= 0;
    var isEmpty = true;

    var abort = false;
    $("div.error").remove();

    //traverse through each required field to ensure it's been filled in - Added this check in to see if it has already been checked...if not then continue...

    if ($(this).hasClass('checked-and-filled') {
       $(':input[required]').each(function() {
          if($(this).val()==='') {
              $(this).after('<div class="error">This is a required field</div>');
              abort = true;
          } else {

             // if the value is not empty then we know its been checked and it has a value
             addClass('checked-and-filled');

          }
       });
       if (abort) { return false;} else {return true;}
    }
});

还有关于您的 HTML 的快速评论。我在你的 fiddle 中注意到了这一点,但我认为你的实际代码中可能有这个错误......

在所有部分句子中,您都以 h3 标签开头,但以 h2 结尾:

<h3 class="center">Part 1 of 5</h2>

关于javascript - 仅验证表单的可见部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46626617/

相关文章:

javascript - Paperjs 中的路径 VS 形状?

javascript - 在基于 iframe 的网站中,当用户单击一个 iframe 中的链接后,如何在新窗口中加载所有 iframe?

jquery - 如何在 Angular 4 中的 $.post 中访问 router.navigate() ?

javascript - 如何创建 Jquery 幻灯片左删除列表项?

html - FontAwesome 水平居中图标

html - Yii框架解释

JavaScript - 在自调用函数中传递回调函数

javascript - 我想编写一个具有良好结构的代码。但我不能

javascript - 如何淡化背景

javascript - 将隐藏图像加载到 HTML