javascript - jQuery 验证插件仅适用于最后显示的 div

标签 javascript jquery jquery-validate

我正在尝试验证我的表单,即 jQuery 显示/隐藏表单。 jQuery 验证插件仅验证我在最后一个 div(输入类型文件)上的最后输入。我目前可以上传图像并成功提交表单,其余输入为空。

下面是第三个 div,当我点击未填写任何输入的帖子广告时,会显示“此字段为必填字段”。 Third Div

下面是第一个没有验证消息的 div First Div

下面是第二个 div,没有验证消息 Second Div

这是我的表格:

<!DOCTYPE html>
<html lang="en">

<head>

   <title>Zootopia</title>

   <script src="http://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

   <script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

</head>

<body>

<form id="ad_form" method="post">

  <div id="ad_form_section1">

    <div class="form-group">
       <label for="ad_title">Ad Title</label>
       <input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title" required>
    </div>

    <div class="form-group">
       <label for="description">Describe what you're offering</label>
       <textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
    </div>

  <button type="button" id="ad_section2" class="btn btn-primary"> Next </button>

  </div>

  <div id="ad_form_section2">

    <div class="form-group">
       <label for="location"> Location</label>
       <input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
    </div>

    <div class="form-group">
       <label for="price">Price</label>
       <input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
    </div>

   <button type="button" id="back_section1" class="btn btn-primary"> Back </button>

   <button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
  </div>

  <div id="ad_form_section3">

    <div>
       <label> Select pet pictures</label>
       <input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
    </div>

    <button type="button" id="back_section2" class="btn btn-primary"> Back </button>

    <input type="hidden" name="action_type" value="add" />

    <input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />

  </div>

</form>

这是我的 JavaScript:

$(document).ready(function(){

  $("#ad_section2").click(function(){
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
  });

  $("#back_section1").click(function(){
      $("#ad_form_section1").show();
      $("#ad_form_section2").hide();
  });

  $("#ad_section3").click(function(){
      $("#ad_form_section3").show();
      $("#ad_form_section2").hide();
  });

  $("#back_section2").click(function(){
      $("#ad_form_section2").show();
      $("#ad_form_section3").hide();
  });

    $("#ad_form").validate({
        rules:{
              ad_title:{
                required: true
              },
              description:{
                required: true
              },
              location:{
                required: true
              }
        },
        messages:{
              ad_title: {
                required: "please enter an ad title"
              },
              description: {
                required: "please enter a description"
              },
              location: {
                required: "please enter a location"
              }
        },
            submitHandler: function(form) {
              var petID = $( "#pet_ad option:selected" ).val();
              var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;

                   $(form).ajaxSubmit({
                      url:addAdUrl,
                      type:"post",
                      datatype: 'json',
                      success: function(result){
                          if(result.petAd == false){
                            alert("Pet ad already exists!");
                          }else{
                            alert("Ad posted!");
                            $('#image_table').hide();
                          }
                      },
                      error: function(error) {
                        alert("Error");
                      }
                  });
            }
      });
})

这是我的 CSS:

#ad_form_section2,
#ad_form_section3{
  display: none;
}

最佳答案

您需要在显示/隐藏下一个字段之前添加条件

if ( $('field-id').valid() ) {
     // Code 
}

例如:

$("#ad_section2").click(function(){
   if ($('#ad_title').valid() && $('#description').valid()) {
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
    }
});

另外,不要忘记设置字符编码以避免字符范围错误,在<head>下面添加以下代码标签:

<meta charset="UTF-8">

表单示例:

$(document).ready(function(){

  $("#ad_form").validate({
    rules:{
      ad_title:{
        required: true,
        minlength: 3, // set minimum title length
      },
      description:{
        required: true,
        minlength: 10,
      },
      location:{
        required: true
      }
    },
    messages:{
      ad_title: {
        required: "please enter an ad title",
        minlength: "Your title must be more than 3 characters!",
      },
      description: {
        required: "please enter a description",
         minlength: "Your description must be at least 10 characters long",
      },
      location: {
        required: "please enter a location"
      }
    },
    submitHandler: function(form) {
      var petID = $( "#pet_ad option:selected" ).val();
      var addAdUrl = "../../controller/post_ad_process.php?petID=" + petID;

      $(form).ajaxSubmit({
        url:addAdUrl,
        type:"post",
        datatype: 'json',
        success: function(result){
          if(result.petAd == false){
            alert("Pet ad already exists!");
          }else{
            alert("Ad posted!");
            $('#image_table').hide();
          }
        },
        error: function(error) {
          alert("Error");
        }
      });
    }
  });

  $("#ad_section2").click(function(){
    // Check if valid before show/hide
    if ($('#ad_title').valid() && $('#description').valid()) {
      $("#ad_form_section1").hide();
      $("#ad_form_section2").show();
    }
  });

  $("#back_section1").click(function(){
    $("#ad_form_section1").show();
    $("#ad_form_section2").hide();
  });

  $("#ad_section3").click(function(){
  // Check if valid before show/hide
    if ($('#location_ad').valid()) {
      $("#ad_form_section3").show();
      $("#ad_form_section2").hide();
    }
  });

  $("#back_section2").click(function(){
    $("#ad_form_section2").show();
    $("#ad_form_section3").hide();
  });
});
#ad_form_section2,
#ad_form_section3 {
  display: none;
}
label.error {
  color: red;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.validate/1.11.1/jquery.validate.min.js"></script>

<div class="container">
  <form id="ad_form" method="post">

    <div id="ad_form_section1">
      <div class="form-group">
        <label for="ad_title">Ad Title</label>
        <input type="text" class="form-control stored" id="ad_title" placeholder="e.g. German Sheperd puppy - 4 months old" name="ad_title">
      </div>
      <div class="form-group">
        <label for="description">Describe what you're offering</label>
        <textarea class="form-control stored" id="description" rows="6" placeholder="e.g. Owner supervised visits, minimum 1hr bookings, play with my german sheperd puppy in my backyard" name="description" required></textarea>
      </div>
      <button type="button" id="ad_section2" class="btn btn-primary"> Next </button>
    </div>

    <div id="ad_form_section2">
      <div class="form-group">
        <label for="location"> Location</label>
        <input type="text" id="location_ad" class="form-control stored" placeholder="location" name="location" required/>
      </div>
      <div class="form-group">
        <label for="price">Price</label>
        <input type="text" id="price" class="form-control stored" name="price" placeholder="$0.00" required/>
      </div>
      <button type="button" id="back_section1" class="btn btn-primary"> Back </button>
      <button type="button" id="ad_section3" class="btn btn-primary"> Next </button>
    </div>

    <div id="ad_form_section3">
      <div>
        <label> Select pet pictures</label>
        <input type="file" name="multiple_files[]" id="multiple_files" multiple required/>
      </div>
      <button type="button" id="back_section2" class="btn btn-primary"> Back </button>
      <input type="hidden" name="action_type" value="add" />
      <input type="submit" id="ad_button" class="btn btn-primary" value="Post ad" />
    </div>

  </form>
</div>

来自 documentation 的更多示例

关于javascript - jQuery 验证插件仅适用于最后显示的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50499233/

相关文章:

javascript - 仅在 React.Js 中更改主页上滚动的标题组件的样式

Jquery 将值传递给 Controller ​​(codeigniter)

javascript - 动态克隆表单的 jQuery 图像验证

jquery 验证数组输入的添加规则

Jquery Validate 不能很好地与 HTML 5 一起工作?

javascript - 从li标签获取图像来源

javascript - 错误未捕获语法错误 : Unexpected token <in JSON at position 0

javascript - 有没有办法检测具有特定类的 div 并将顶部滚动条移动到其父 div 内的位置?

javascript - SAP UI5 搜索 - 绑定(bind)到 XML View

php - 在登录表单中禁用自动完成输入文本