Problem with validations in dynamic inputs with ajax?

1

I have a problem, I have a code to generate dynamic inputs that in turn sends a function in laravel to insert several records at the same time in the database.

This is the code that generates the inputs

$(document).ready(function() {

        var c = 100;
        $('#addCat').on('click',function(e){
            e.preventDefault();

        var formularioCat =  '<div  class="form-group CategoriaDinamica" >';
            formularioCat+=         '<label for="categoria" class="col-md-4 control-label">Categoria '+c+'</label>';
            formularioCat+=          '<div class="col-md-6">';

            formularioCat+=              ' <input  class="form-control" name="categoriadinamica[]" type="text" value="">';                      
            formularioCat+=          ' </div>';                            
            formularioCat+=   ' </div>';   


            $(formularioCat).hide().insertBefore('#botonenvio').fadeIn(500);

            c++;

        })

        $('#removeCat').on('click',function(r){
            r.preventDefault();
            $('#botonenvio').prev().remove();


        })

I have this code for future validations

this.addynotificacion = function(campoaiterar,nombrearray,estado,mensaje){
    $(campoaiterar).each(function(i) {
            nombrearray.push($(this).val());
                if(nombrearray[i]=='')
                    {
                         $('.jumbotron').before(notificacion(estado,mensaje));  

                        return false;
                    }   

        });


}

And this is the ajax function

$(document).ready(function() {
    $('#bsubmit').click(function(e){

        e.preventDefault();
        var rutaCompleta = 'http://localhost/ficheros/public/admin/categorias';

        var namecatdin = $('input[name="categoriadinamica[]"]');
        var datos = [];


                addynotificacion(
                namecatdin,
                datos,
                'danger',
                'NO PUEDES DEJAR UNA CATEGORIA EN BLANCO :: LAS SIGUIENTES NO SE INSERTARAN');

            $.ajax({
                    url: rutaCompleta,
                    method: 'POST',
                    data: {'datosarray':datos},
                    headers: { 'X-CSRF-TOKEN': $('meta[name="_token"]').attr('content') },
                })
                .done(function(datosarray) {
                    console.log("success_creacion_"+$.type(datosarray));
                    var muchosdata = [];
                    addynotificacion(
                        namecatdin,
                        muchosdata,
                        'success',
                        'REGISTRO ..:: '+muchosdata[i]+' ::.. CREADO CORRECTAMENTE'
                        );          


                    })
                .fail(function(x) {
                    console.log(' nombre_error: '+x.errorThrown);
                })
                .always(function() {
                    console.log("complete");
                });

    })
});

The problem is that I think I can not think of how to enter the validation, since if it were a single input to be introduced in the bbdd there would be no problem but with more than one I am failing, it makes me the first validation well and then I insert the records in the following, in this case the validation checks that the record is not blank, because the first record does not enter it in the database but all the following ones are entered as blank characters, the obvious idea is put more validations, but first I have to work with the first one and evaluate all the records and then use the ajax function.

Then as something apart

This function gives me this error

this.addynotificacion = function(campoaiterar,nombrearray,estado,mensaje){
        $(campoaiterar).each(function(i) {
                nombrearray.push($(this).val());
                    if(nombrearray[i]=='')
                        {
                             $('.jumbotron').before(notificacion(estado,mensaje));  

                            return false;
                        }   

            });


    }

ReferenceError: i is not defined

How can I adjust it to use it correctly in the other function?

Thank you for your time.

    
asked by KurodoAkabane 30.12.2016 в 18:27
source

1 answer

0

Friend to your input you have to put a class to go. and the each apply to it. as for example:

$('.checked').each(function(){
     $(this).attr('id');
});

In the function that I put you, you go through all those with the "checked" class and from each one you take that object and you can extract the value you want. by having the value you can send it to the ajax function one by one or you can do a .push in an array to send the entire array.

try not to place the complete route on the route. Only the route of the page that you place in Route::get('categorias'); remembers that this way you avoid changing the routes when going to production or making changes.

I hope it helps you.

    
answered by 04.01.2017 в 14:59