简体   繁体   English

jQuery验证插件无法验证动态选择

[英]Jquery validation plugin not validate dynamic select

Hello I'm having trouble with validation on dynamic select box. 您好,我无法在动态选择框上进行验证。 Jquery validation not validate the rest of dynamic select box instead the existing one. jQuery验证不会验证其余的动态选择框,而不会验证现有的选择框。 Noted that I'm using CakePHP 2.5, Bootstrap 3 , and Jquery validation. 注意,我正在使用CakePHP 2.5,Bootstrap 3和Jquery验证。

Below is my code. 下面是我的代码。

HTML HTML

<?php echo $this->Form->create('Redemption',array('type'=>'file','id'=>'redeemForm')); ?>
    <div class="form-group">
       <div class="row"  id="proRow_0">
            <div class="col-md-4">
                <label>Product Purchased</label>
                    <?php echo $this->Form->input('Product.0.type_id',array('class'=>'form-control product-select','id'=>'product_0','label'=>false,'empty'=>array(''=>'Choose Product'),'div'=>false));?>
                </div>                      
            </div>
    </div>
    <div id="moreProduct"></div>
    <a id="add"><i class="fa fa-plus-circle"></i> Add More</a>
   <a id="remove"><i class="fa fa-minus-circle"></i> Remove</a> 

Javascript 使用Javascript

    $('#add').on('click', function(event) {
        event.preventDefault(); 
        rmBtn.show();

        var productRow = $('#moreProduct');

        $.get('<?php echo $this->webroot;?>/redemptions/getProductType.json', function(data) {

            var proRow = 'proRow_'+index;
            var modelID = 'model_'+index;
            var quantityID = 'quantity_'+index;
            var newPRow = '<div class="row moreProduct" id="'+proRow+'">';

            newPRow += '<div class="col-md-4 product-type-field">';
            newPRow += '<select class="form-control product-select" name="data[Product]['+index+'][type_id]" id="product_'+index+'">';
            newPRow += '<option>Choose Product</option>';
            $.each(data,function(key, val) {
                newPRow += "<option value=\""+key+"\">"+val+"</option>";
            });

            newPRow += '</select></div><div class="col-md-4 product-model-field" id="'+modelID+'"></div><div class="col-md-4 product-quantity-field" id="'+quantityID+'"></div>';
            productRow.append(newPRow);

            var productTfield = $('.product-type-field');
            var productMfield = $('.product-model-field');
            var productQfield = $('.product-quantity-field');

            //assign new style
            $('#moreProduct').css({'margin-top': '-10px'});
            productTfield.css({'margin-top': '10px'});
            productMfield.css({'margin-top': '10px'});
            productQfield.css({'margin-top': '10px'});


            $('select[name*="type_id"]').each(function() {
                $(this).on('change', function(event) {
                    event.preventDefault();

                    var proID = $(this).val();
                    var modelID = $(this).attr('id').substring(8);
                    var quantityID = $(this).attr('id').substring(8);
                    var modelID = $('#'+proRow).find($('#model_'+modelID)).attr('id');
                    var quantityID = $('#'+proRow).find($('#quantity_'+quantityID)).attr('id');


                    if (modelID) {
                        var productMfield = $('div[id^="'+modelID+'"]');
                        var productQfield =  $('div[id^="'+quantityID+'"]');

                        $.post("<?php echo $this->webroot;?>/redemptions/getProductModel.json",{proID : proID}).done(function(data){
                            productMfield.html("");

                            var modelVal = modelID.substring(6);
                            var quantityVal = quantityID.substring(9);
                            var modelSelect = '<select class="form-control model-select" name="data[Product]['+modelVal+'][model_id]">';

                            $.each(data,function(key, val) {
                                modelSelect += "<option value=\""+val.Product.id+"\">"+val.Product.product_model+"</option>";
                            });

                            modelSelect += '</select>';
                            productMfield.append(modelSelect);

                            productQfield.html();

                            var newQuantity = '<input type="text" class="form-control quantity" placeholder="Quantity" id="qval_'+quantityVal+'"name="data[Product]['+modelVal+'][quantity]">';

                            productQfield.append(newQuantity);

                            quantityID = $('#'+proRow).find($('#qval_'+quantityVal)).attr('id');
                            quantityID = $('#'+quantityID);
                            qListener(quantityID);

                        });
                    }else{
                        existFieldListener();
                    };
                });
            });
        });
        index++;
    });


function formValidation(){
        $.validator.setDefaults({
            highlight: function (element, errorClass, validClass) {
                // console.log(element.type);
                // console.log(this.findByName(element.name));
                if (element.type == 'radio') {
                    this.findByName(element.name).addClass(errorClass).removeClass(validClass);
                } else if(element.type == 'select-one'){
                    console.log('yes');
                    console.log(errorClass);
                    console.log($('select-one'));
                    $('select-one').each(function() {
                        $(this).removeClass('has-success has-feedback').addClass('has-error has-feedback');
                    });
                    // $(element).closest('.product-type-field').removeClass('has-success has-feedback').addClass('has-error has-feedback');
                }else if(element.name == 'data[Redemption][retailer_id]'){
                    $(element).closest('.form-group').find('i.fa').remove();
                }else {
                    $(element).closest('.form-group').removeClass('has-success has-feedback').addClass('has-error has-feedback');
                    $(element).closest('.form-group').find('i.fa').remove();
                }
            },
            unhighlight: function (element, errorClass, validClass) {
                if (element.type === "radio") {
                    this.findByName(element.name).removeClass(errorClass).addClass(validClass);
                } else {
                    $(element).closest('.form-group').removeClass('has-error has-feedback').addClass('has-success has-feedback');
                    $(element).closest('.form-group').find('i.fa').remove();
                }
            }
        });

        $.validator.addMethod("accept", function(value, element, param) {
            return value.match(new RegExp("." + param + "$"));
        }); 


        $('#redeemForm').validate({
            debug:true, 
            ignore: '*:not([name])',
            submitHandler: function(form) {
                form.submit();
            },
            accept: function(value, element, param) {
                return value.match(new RegExp("." + param + "$"));
            },
            rules: {
                "data[Redemption][date_purchased]":{
                    required:true,
                },
                "data[Redemption][invoice_no]":{
                    required:true,
                },
                "data[Customer][customer_name]":{
                    required:true,
                },
                "data[Product][0][type_id]":{
                    required:true,
                },

                "data[Customer][primary_address]":{
                    required:true,
                },
                "data[Customer][nric_no]":{
                    required:true,
                    accept:"[a-zA-Z0-9]+",
                }, 
                "data[Redemption][invoice]":{
                    required:true,
                },
                "data[Customer][customer_email]":{
                    required:true,
                    email:true,
                },
                "data[Customer][contact_no]":{
                    required:true,
                    number: true
                },
                "data[Customer][city]":{
                    required :true,
                    accept: "[a-zA-Z]+",
                },
                "data[Customer][postal_code]":{
                    required :true,
                    accept: "[0-9]+",
                },
                "data[Customer][state]":{
                    required :true,
                },
            },
            messages:{
                "data[Customer][customer_email]":{
                    email: "Your email address must be in the format of name@domain.com"
                },
                "data[Customer][contact_no]":{
                    number: "Your contact must be in the format of 03xxxxxx/019xxxxxx"
                },
                "data[Customer][city]":{
                    accept:"Accept letter only"
                },
                "data[Customer][postal_code]":{
                    accept:"Accept number only"
                }, 
                "data[Customer][nric_no]":{
                    accept:"NRIC no. must be in in the format of 123456xxxxxx without '-'"
                }
            },
            setDefaults: {
                ignore: ":hidden:not(select)",
            },
            errorElement: 'span',
            errorClass: 'help-block',
            errorPlacement: function(error, element) {
                if(element.parent('.input-group').length) {
                    error.insertAfter(element.parent());
                } else if (element.is('#retailers')) {
                    error.insertAfter(element.siblings(".chzn-container"));
                } else {
                    error.insertAfter(element);
                }
            },
        });
    $('#redeemForm').on('submit', function() {
        $(this).validate();
        // $('input').each(function () {
        //  $(this).rules('add', {
        //      required: true,
        //  });
        // });
        $('select[name*="type_id"]').each(function() {
            // console.log($(this));
            $(this).rules('add',{
                required:true,
            });
        });
    });


}

Really appreciate your help and time. 非常感谢您的帮助和时间。 Thanks 谢谢

First, don't attach anything to the submit event, instead use the submitHandler option of the $.validate call: 首先,不要在submit事件中附加任何内容,而应使用$.validate submitHandler调用的submitHandler选项:

$('#redeemForm').validate({
  submitHandler:function(){
    //This is called when the form successfully submits with no validation errors
  }
});

Second, you need to attach the validation to the select right after you append it to the row. 其次,在将验证附加到行之后,需要将验证附加到选择权。 So, in your $.get handler, after you append the row, add your validation: 因此,在$.get处理程序中,在追加行之后,添加验证:

 //in your $.get handler
 productRow.append(newPRow);

 $('#product_'+index).rules('add',{
    required: true
 });

 var productTfield = $('.product-type-field');

 //...and it continues after here

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

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