DubFriend / jquery.repeater

Create a repeatable group of input elements
MIT License
389 stars 191 forks source link

How to specify the configuration of nested repeaters and how to reference them? #98

Open martinmurciego opened 5 years ago

martinmurciego commented 5 years ago

Congratulations is very useful this plugin would only add a behavior that renders id attributes of repeated elements. But my questions is about his example of Nested Repeater: a) how to specify the properties of nested repeaters having specified for the outer repeater? b) And how is reference made to inner repeater to specify behaviors with show (), hide () and ready ()? For example, I have a table inside an outer repeater of the accordion panel, that is, a table nested inside another element that is already repeated. As I specify that every time I add a row, the row in the first column is listed, when I do not know how to refer to an item added in the inner repeater, although it can be referenced to the outer repeater? If you do not understand this last I want to say how I specify the function show () for an inner repeater?

<script src="path/to/jquery.js"></script>
<script src="path/to/jquery.repeater/jquery.repeater.js"></script>
<script>
    $(document).ready(function () {
        $('.repeater').repeater({
            // (Required if there is a nested repeater)
            // Specify the configuration of the nested repeaters.
            // Nested configuration follows the same format as the base configuration,
            // supporting options "defaultValues", "show", "hide", etc.
            // Nested repeaters additionally require a "selector" field.
            repeaters: [{
                // (Required)
                // Specify the jQuery selector for this nested repeater
                selector: '.inner-repeater'
            }]
        });
    });
</script>
martinmurciego commented 5 years ago

It seems I understood something about how to do it. If you have any suggestions or examples that extend my knowledge welcome. Congratulations again for this library!

<script type="text/javascript">
        // JQUERY.REPEATER REPETIR ELEMENTOS
        $(document).ready(function() {
            //Boton Nuevo antes de repetirse para agregar periodos de reserva de espacio, para desactiva link
            $("button[name *='nuevoPeriodo']").click(function(e){ 
                e.preventDefault();
                return false;
            }); 

            var $repeater = $('.repeater').repeater({
                initEmpty: false,
                defaultValues: {},
                repeaters: [{ 
                    initEmpty: false,
                    defaultValues: {},
                    selector: '.repeater-espaciados-periodos',
                    show: function() { //al agregar item con .slideDown()
                        var selfRepeaterItem = this;
                        console.log('se agrega periodo:\n\t', selfRepeaterItem);
                        $(selfRepeaterItem).slideDown(); 
                    },
                    hide: function(deleteElement) {
                        //Dialogo de Confirmacion modal con bootbox
                        var ctx = $(this);
                        bootbox.confirm({
                            title: '<h4>El registro será eliminado!</h4',
                            message: '<h2>¿Está seguro seguro que desea quitar esta configuración?</h2>',
                            buttons:{
                                confirm:{
                                    label: '<i class="fa fa-check"></i> Si',
                                    className: 'btn-success'
                                },
                                cancel:{
                                    label: '<i class="fa fa-times"></i> No',
                                    className: 'btn-danger'
                                }
                            },
                            callback: function (result){
                                if (result){
                                    //Actualiza badge contador del panel title
                                    //eliminar elementos repeteables
                                    ctx.slideUp(deleteElement);
                                    //Actualizar indices en el titulo
                                    $("div[data-repeater-item]").not(deleteElement).each(function(index, value){
                                        console.log('index: ', index);
                                        console.log('value: ', value);
                                        //$(value).find('a > h4 > span.repeaterItemNumber').text(index + 1);
                                    })
                                } else{
                                    return;
                                }
                            }
                        });
                    }
                }],
                show: function() { //al agregar item con .slideDown()
                    var selfRepeaterItem = this;
                    console.log('se agrega espacio:\n\t', selfRepeaterItem);
                    $(selfRepeaterItem).slideDown();

                    var repeaterItems = $("div[data-repeater-item] > div.panel");
                    $(selfRepeaterItem).attr('data-index', repeaterItems.length - 1);
                    $(selfRepeaterItem).find('a  h4 span.repeaterItemNumber').text(repeaterItems.length);

                    var aheadingItemId = '#headingItem' + repeaterItems.length;
                    $(selfRepeaterItem).find('a.panel-heading').attr('id', aheadingItemId).attr('href', '#collapseItem' + repeaterItems.length).attr('aria-controls', 'collapseItem' + repeaterItems.length);

                    $(selfRepeaterItem).find('#collapseItem').attr('id', 'collapseItem' + repeaterItems.length).attr('aria-labelledby', 'headingItem' + repeaterItems.length);

                    // if (repeaterItems.length > 1) 
                    //     $(this).prepend('<hr />');

                    $("#headingEspacios > h4 > span i.repeaterItemCounter").text(repeaterItems.length);
                    $("#headingEspacios > h4 > span i.repeaterItemCounter").attr('title', 'Espacio(s) reservado(s): ' + repeaterItems.length);

                    var cargarRepeatedSelect2 = async function () {
                        //inicializarSelect2("[name *='reservas'][");
                        //Espacios de Reunion
                        var espacioControls = $("[name *='reservas'][name *='[espacio]']");

                        var lastIndex = repeaterItems.length -1;//espacioControls.length - 1;
                        var controlEspacio = "[name*='reservas[" + lastIndex + "][espacio]'";
                        //inicializarSelect2(controlEspacio);
                        console.log('controlEspacio: ', controlEspacio, '\n\t', "select[name~='reservas[0][espacio]']");
                        //$('.select2-container').remove();
                        var fr1 = await cargarSelect2Espacios(controlEspacio);

                        //Formatos de Evento
                        var formatoControls = $("[name *='reservas'][name *='[formatoEvento]']");
                        var lastIndex = repeaterItems.length -1;//formatoControls.length - 1;
                        var controlFormato = "[name~='reservas[" + lastIndex + "][formatoEvento]'";
                        //inicializarSelect2(controlFormato);
                        console.log('controlFormato: ', controlFormato);
                        var fr2 = await cargarSelect2FormatosEvento(controlFormato);

                        //Quitar la parte del select que se visualiza repetido a lado como un bug al clonar
                        console.log('selfRepeaterItem: ', selfRepeaterItem);
                        $(selfRepeaterItem).find('select').next('.select2-container').remove();
                          //$(selfRepeaterItem).find('select').select2();
                          //$('.select2-container').remove();
                          // $('.select2Control').select2({
                          //     placeholder: "Placeholder text",
                          //     allowClear: true
                          // });
                          // $('.select2-container').css('width', '100%');   

                        return true;
                    };

                    cargarRepeatedSelect2();
                    initDateTimePicker("div[data-repeater-item][data-index='" + (repeaterItems.length - 1) +  "'] "); //Inicializar nuevo datetimepicker
                    establecerMascaraControles(); //inicializar mask a dateTimePicker repetidos y otros input

                    //Boton Nuevo repetido para agregar periodos de reserva de espacio, para desactiva link
                    $("button[name *='nuevoPeriodo']").click(function(e){ 
                        e.preventDefault();
                        return false;
                    }); 

                },
                hide: function(deleteElement) {
                    //Dialogo de Confirmacion modal con bootbox
                    var ctx = $(this);
                    bootbox.confirm({
                        title: '<h4>El registro será eliminado!</h4',
                        message: '<h2>¿Está seguro seguro que desea quitar esta configuración?</h2>',
                        buttons:{
                            confirm:{
                                label: '<i class="fa fa-check"></i> Si',
                                className: 'btn-success'
                            },
                            cancel:{
                                label: '<i class="fa fa-times"></i> No',
                                className: 'btn-danger'
                            }
                        },
                        callback: function (result){
                            if (result){
                                //Actualiza badge contador del panel title
                                var repeaterItems = $("div[data-repeater-item] > div.panel");
                                $("#headingEspacios > h4 > span > i.repeaterItemCounter").text(repeaterItems.length -1);
                                $("#headingEspacios > h4 > span i.repeaterItemCounter").attr('title', 'Espacio(s) reservado(s): ' + repeaterItems.length);

                                //eliminar elementos repeteables
                                ctx.slideUp(deleteElement);
                                //Actualizar indices en el titulo
                                $("div[data-repeater-item]").not(deleteElement).each(function(index, value){
                                    //console.log('index: ', index);
                                    //console.log('value: ', value);
                                    $(value).find('a > h4 > span.repeaterItemNumber').text(index + 1);
                                })
                            } else{
                                return;
                            }
                        }
                    });
                },
                // (Optional)
                // You can use this if you need to manually re-index the list
                // for example if you are using a drag and drop library to reorder
                // list items.
                ready: function(setIndexes) {
                    // console.log('ready: ', setIndexes);
                    // setIndexes();
                    //$dragAndDrop.on('drop', setIndexes);

                    //Actualizar indices en el titulo
                    //$("div[data-repeater-item]").each(function(index, value){
                        //console.log('ready:\n\t')
                        //console.log('index:' + index + '\n\t'); //index desde cero
                        //console.log('value:', value); //value es el item o elmento html <div>...</div>
                        //value.attr('data-index', index);
                        //$(value).find('a > h4 > span.repeaterItemNumber').text(index + 1);
                    //});
                },
                // (Optional)
                // Removes the delete button from the first list item,
                // defaults to false.
                isFirstItemUndeletable: true
            })
            /*  Valores devueltos para enviar a server con POST HTTP*/
            var reservas = $('.repeater').repeaterVal();

        });
    </script>