简体   繁体   English

jQuery validate,如何为动态生成的字段制定验证规则?

[英]jQuery validate , how to make validation rules for dynamically generated fields?

I have an HTML form with dynamically add more fields.我有一个动态添加更多字段的 HTML 表单。 For example company name.例如公司名称。 I am trying to use the jQuery validate method to validate.我正在尝试使用 jQuery 验证方法进行验证。 It is working fine with the existing company name field.它适用于现有的公司名称字段。 Here is the code.这是代码。

<script>
     $("#company_creation_form").validate({ 
            rules:{
                company_name: { 
                    required: true, 
                    minlength: 3 
                }

            },
            submitHandler: function (form) {
             $.ajax({
                 type: "POST",
                 url: "<?php echo BASE_URL;?>crm/thankyou/",
                 data: $(form).serialize()+"&company_count="+company_count,
                 success: function () {
                     alert("thanks");                     
                 }
             });
             return false; // required to block normal submit since you used ajax
         }
     });
</script>

When I click on add more button another company name field will create on the form.当我单击添加更多按钮时,将在表单上创建另一个公司名称字段。 The below code is failed to validate the dynamically generated field.以下代码无法验证动态生成的字段。 Here I am getting the field count globally in this variable company_count在这里,我在这个变量company_count中全局获取字段计数

<script>
     $("#company_creation_form").validate({ 
            rules:{
                company_name: { 
                    required: true, 
                    minlength: 3 
                },

I tried like below, but this is giving me error

            if(company_count> 0){
                var new_field = jQuery("#company_name"+company_count);
                new_field : { 
                                required: true, 
                                minlength: 3 
                            },
                        }

The above block code is showing error in the text editor it self

},
submitHandler: function (form) {
             $.ajax({
                 type: "POST",
                 url: "<?php echo BASE_URL;?>crm/thankyou/",
                 data: $(form).serialize()+"&company_count="+company_count,
                 success: function () {
                     alert("thanks");                     
                 }
             });
          return false; // required to block normal submit since you used ajax
         }
     });
</script>

Can anyone help me with how to make validation for these dynamically generated fields?谁能帮助我对这些动态生成的字段进行验证? Any help would be greatly appreciated.任何帮助将不胜感激。 I am using form submission by using Ajax . I am using form submission by using Ajax Code to add company fields dynamically

var company_room = 0;
var company_room1 = 0;
function add_another_company() {
    company_room++;
    company_room1++;
    var objTo = document.getElementById('company_field')
    var divtest = document.createElement("div");
    divtest.setAttribute("class", "form-group removeclass2" + company_room);
    //var rdiv = 'removeclass2' + company_room;
    divtest.innerHTML = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="company_name" name="company_name" placeholder="Company Name"></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button" onclick="remove_another_company(' + company_room + ');"> <i class="fa fa-minus"></i> </button> </div></div></div>';

    objTo.appendChild(divtest);
    var E_fields = $('.aj4');
    var E_count = 1;
    $.each(E_fields, function() {
        jQuery(this).attr('id','company_name' + E_count);
        jQuery(this).attr('name','company_name' + E_count);
        E_count++;
    });
}

function remove_another_company(rid2) {
        company_room1--;
        $('.removeclass2' + rid2).remove();
        var E_fields = $('.aj4');
        var E_count = 1;
        $.each(E_fields, function() {
            jQuery(this).attr('id','company_name' + E_count);
            jQuery(this).attr('name','company_name' + E_count);
            E_count++;
        });
}

OK, so I didn't have your HTML so I had to mock some up.好的,所以我没有你的 HTML 所以我不得不模拟一些。 You will obviously have to tweak this a little to work with your ID's.您显然必须稍微调整一下才能使用您的 ID。 I tried to keep it as close as possible to the ID's/classes you were already using.我试图让它尽可能接近您已经使用的 ID/类。

I removed the pure javascript functions and the onclick events in favor of jquery since you were already using it.我删除了纯 javascript 函数和 onclick 事件以支持 jquery,因为您已经在使用它。 Hopefully this kind of simplifies things a bit and makes it more manageable.希望这种方式可以简化一些事情并使其更易于管理。

NOTE: I added a hidden input field to keep track of company count.注意:我添加了一个隐藏的输入字段来跟踪公司数量。 This way it will be included when you $(form).serialize in your ajax options (as you are adding it with a variable now).这样,当您 $(form).serialize 在您的 ajax 选项中时,它将被包含在内(因为您现在正在使用变量添加它)。 I included code to preserve the company_count variable also, so basically you will have 2 company counts.我还包含了保留 company_count 变量的代码,所以基本上你将有 2 个公司计数。 I did this just to show you an easier way to keep track of this without having to micro manage it.我这样做只是为了向您展示一种更简单的方法来跟踪它,而无需对其进行微观管理。 :) :)

Try out this code and let me know what your getting in console if it is not working.试试这个代码,如果它不起作用,让我知道你在控制台中得到了什么。 Thanks谢谢

MOCK HTML模拟 HTML

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="form-wrapper">
  <p>Dynamic Form</p>
  <button id="addField">Add Dynamic Field</button>
  <form id="dynForm">
    Static Field: <input id="company_name" name="company_name" minlength="3" type="text" value="Static Company Name" required>
    <br>
    <input type="hidden" id="companyCount" name="companyCount" value="1">
    <div id="company_field">

    </div>

  </form>
</div>

JQUERY/JS查询/JS

$(function() {  // <---- Document Ready!
  $("#addField").on("click", () => {
    var count = parseInt($("#companyCount").val(), 10);
    count += 1;
    $("#companyCount").val(count.toString());
    var thisId = "company_name" + count.toString();
    var html = '<div class="form-row"><div class="col-sm-5"> <div class="form-group pad-tp-5"><input type="text" class="form-control aj4" id="'+thisId+'" name="'+thisId+'" minlength="3" placeholder="Company Name" required></div></div><div class="col-sm-2"> <div class="form-group"> <button class="btn btn-danger bdr-rds-100 btn-pad" type="button"> <i class="fa fa-minus"></i> </button> </div></div></div>';
    var ele = $.parseHTML(html);

    $("#company_field").append(ele);

  });

  $("#company_field").on("click", "button", () => $(this).closest(".form-row").remove());


    $("#company_creation_form").validate({
      submitHandler: function(form) {
        var company_count = parseInt($("#companyCount").val(), 10);
        $.ajax({
          type: "POST",
          url: "<?php echo BASE_URL;?>crm/thankyou/",
          data: $(form).serialize() + "&company_count=" + company_count,
          success: function() {
            alert("thanks");
          }
        });
        return false; 
      }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM