1

¿Cómo puedo obtener los id's borrados de varios botones en una sola variable? pero el problema que tengo es que si es un array al pasar de un modal a otro es como que si el array no se limpiara y se clonara por lo cual no encuentro manera de solucionarlo, ayuda por favor. Si conocen una mejor forma de almacenar múltiples id´s en una sola variable al ser cliqueadas en el boton de eliminar seria de mucha ayuda muchas gracias. Esto quiero hacerlo para pasar esas id´s a una solicitud ajax que recibe un controlador en codeigniter.

Este es el modal donde lo llamo con un evento en javascript

<div id="modalEditarOtPloteo"
     class="modal fade"
     tabindex="-1">
    <div class="modal-dialog modal-sm">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">Editar Orden de Trabajo Ploteo</h5>
                <button type="button"
                        class="close"
                        data-dismiss="modal">&times;
                </button>
            </div>
            <div class="modal-body">
                <form action=""
                      method="post"
                      id="formularioPloteo">
                    <div class="form-group row">
                        <div class="col-sm-6">
                            <label for="editarTipoDocumentoPloteo">Tipo de Documento</label>
                            <select id="editarTipoDocumentoPloteo"
                                    name="editarTipoDocumentoPloteo"
                                    class="form-control"
                                    data-fouc
                                    required
                                    disabled="disabled">
                                <?php foreach ($tipoDocumentoPloteo as $documento): ?>
                                    
                                    <option value="<?= $documento->ID_Documento ?>"><?= $documento->Nombre_Documento
                                        ?></option>
                                <?php endforeach; ?>
                            </select>
                            <input type="hidden"
                                   id="editarDataDocumentoPloteo"
                                   name="editarDataDocumentoPloteo">
                            <input type="hidden"
                                   id="editarIdDocumentoPloteo"
                                   name="editarIdDocumentoPloteo">
                            <input type="hidden"
                                   id="editarImpuestoDocumentoPloteo"
                                   name="editarImpuestoDocumentoPloteo">
                            <input type="hidden"
                                   id="editarIdOtPloteo"
                                   name="editarIdOtPloteo">
                        </div>
                        <div class="col-sm-3">
                            <label for="editarSerieDocumentoPloteo">Serie</label>
                            <input type="text"
                                   name="editarSerieDocumentoPloteo"
                                   id="editarSerieDocumentoPloteo"
                                   class="form-control"
                                   disabled>
                        </div>
                        <div class="col-sm-3">
                            <label for="editarNumeroDocumentoPloteo">Número</label>
                            <input type="text"
                                   name="editarNumeroDocumentoPloteo"
                                   id="editarNumeroDocumentoPloteo"
                                   class="form-control"
                                   disabled>
                        </div>
                    </div>
                    <div class="form-group">
                        <label for="editarClientePloteo">Cliente</label>
                        <select id="editarClientePloteo"
                                name="editarClientePloteo"
                                class="form-control select-search"
                                data-placeholder="Seleccione un cliente"
                                data-fouc
                                required>
                            <option></option>
                            <?php foreach ($clientePloteo as $value): ?>
                                
                                <option value="<?= $value->ID_Cliente ?>"><?= $value->Nombre_Cliente . ' ' . $value->Apellido_Cliente ?></option>'
                            
                            <?php endforeach; ?>
                        </select>
                    </div>
                    <div class="form-group row">
                        <div class="col-sm-5">
                            <label for="editarMetrosPloteo">Metros de Ploteo</label>
                            <input type="text"
                                   name="editarMetrosPloteo"
                                   id="editarMetrosPloteo"
                                   class="form-control"
                                   placeholder="1.75">
                        </div>
                        <div class="col-sm-7 align-self-end text-right">
                            <button href="#"
                                    id="editarAgregarPloteo"
                                    class="btn btn-block btn-success btn-icon"
                                    type="button"><i class="icon-trash"></i> Agregar
                            </button>
                        </div>
                    </div>
                    <div class="form-group">
                        <div class="table-responsive">
                            <table class="table table-bordered tablaEditarAgregarPloteo">
                                <thead>
                                    <tr>
                                        <th>Metros</th>
                                        <th>Precio Final</th>
                                        <th>Acción</th>
                                    </tr>
                                </thead>
                                <tbody>
                                
                                </tbody>
                            </table>
                        </div>
                    </div>
                    <div class="form-group row">
                        <div class="col-md-4">
                            <label for="editarSubtotalPloteo">Subtotal:</label>
                            <input type="text"
                                   class="input form-control"
                                   name="editarSubtotalPloteo"
                                   id="editarSubtotalPloteo"
                                   readonly
                                   required>
                        </div>
                        <div class="col-md-4">
                            <label for="editarIvaPloteo">IVA:</label>
                            <input type="text"
                                   class="input form-control"
                                   name="editarIvaPloteo"
                                   id="editarIvaPloteo"
                                   readonly
                                   required>
                        </div>
                        <div class="col-md-4">
                            <label for="editarTotalPloteo">Total:</label>
                            <input type="text"
                                   class="input form-control"
                                   name="editarTotalPloteo"
                                   id="editarTotalPloteo"
                                   readonly
                                   required>
                        </div>
                    </div>
                    <div class="text-center">
                        <button class="btn bg-primary-800"
                                type="button"
                                id="editarOrdenTrabajoPloteo">Editar Orden de Trabajo <i
                                    class="icon-paperplane
                                    ml-2"></i></button>
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

Este es el javascript con todos los eventos

/* EDITAR ORDEN DE TRABAJO PLOTEO */

$(document).on('click', '#editarOtPloteo', function (event) {
    
    event.preventDefault()
    
    let idEditarOtPloteo = $(this).attr('value')
    // alert(idEditarOtPloteo)
    
    $.ajax({
        url: 'http://localhost/ci3/ploteo/editar',
        type: 'post',
        dataType: 'json',
        data: {
            idEditarOtPloteo: idEditarOtPloteo
        },
        success: function (data) {
            
            
            // console.log(metros)
            /* IMPRESION DE LOS VALORES EN CADA INPUT DEL MODAL EDITAR ORDEN DE TRABAJO PLOTEO */
            $('#editarIdOtPloteo').val(data.post[0].ID_OTPloteo)
            $('#editarIdDocumentoPloteo').val(data.post[0].ID_Documento)
            $('#editarImpuestoDocumentoPloteo').val(data.post[0].Impuesto_Documento)
            $('#editarTipoDocumentoPloteo').val(data.post[0].ID_Documento).trigger('change')
            $('#editarSerieDocumentoPloteo').val(data.post[0].Serie_OTPloteo)
            $('#editarNumeroDocumentoPloteo').val(data.post[0].NumeroDocumento_OTPloteo)
            $('#editarClientePloteo').val(data.post[0].ID_Cliente).trigger('change')
            $('#editarSubtotalPloteo').val(data.post[0].Subtotal_OTPloteo)
            $('#editarIvaPloteo').val(data.post[0].Impuesto_OTPloteo)
            $('#editarTotalPloteo').val(data.post[0].Total_OTPloteo)
            
            /* LIMPIAR LA MINITABLA AL PASAR DE MODAL EN MODAL */
            $('.tablaEditarAgregarPloteo tbody').empty();
            
            /* RECORRER CADA DATO DE LA RESPUESTA DEL CONTROLADOR PARA IMPRIMIRLO EN LA MINITABLA */
            data.post[1].forEach(item => {
                // Crea contenido HTML de la fila
                // Agrega un campo oculto para saber qué es lo que se está modificando
                let html = `<tr>
                                        <td>
                                            <input type="hidden" name="editarIdPloteo[]" value="${item.ID_OTPloteo}">
                                            <input type="text" name="editarMetrosTotalPloteo[]" class="editarMetrosTotalPloteo form-control" value="${item.Precio_OTPloteo}">
                                        </td>
                                        <td>
                                            <input type="text" class="form-control editarImporteMetrosPloteo" name="editarImporteMetrosPloteo[]" value="${(item.Importe_OTPloteo)}" readonly>
                                        </td>
                                        <td>
                                        <input type="hidden" name="editarIdDetallePloteo[]" value="${(item.ID_DetalleOTPloteo)}">
                                            <button href="#" id="eliminarMetros" value="${(item.ID_DetalleOTPloteo)}" class="eliminarMetros btn btn-danger btn-icon" type="button"><i class="icon-trash"></i></button>
                                        </td>
                                </tr>`;
                
                /* DIBUJO EN EL HTML DE LA TABLA CON LOS DATOS DE LA BASE DE DATOS */
                $('.tablaEditarAgregarPloteo').append(html);
                
            });
            
            /* AGREGAR FILAS A LA MINI TABLA EDITAR OT PLOTEO */
            $('#editarAgregarPloteo').on('click', function () {
                
                /* OBTENCION DEL VALOR DEL INPUT */
                let datos = $('#editarMetrosPloteo').val()
                
                if (datos != '') {
                    
                    /* PROCESO PARA AUMENTAR LAS FILAS EN LA TABLA PARA AGREGAR METROS */
                    tabla = `<tr>`;
                    tabla += `<td><input type="text" name="editarMetrosTotalPloteo[]" class="editarMetrosTotalPloteo form-control" value="${datos}"></td>`;
                    tabla += `<td><input type="text" class="form-control editarImporteMetrosPloteo" name="editarImporteMetrosPloteo[]" value="${(datos * 1.25).toFixed(2)}" readonly></td>`;
                    tabla += `<td><a href="#" id="eliminarMetros" value="" class="eliminarMetros btn btn-danger btn-icon" type="button"><i class="icon-trash"></i></a></td>`;
                    tabla += `</tr>`;
                    
                    /* DIBUJAR LA TABLA EN LA TABLA RESPECTIVA EN EL HTML */
                    $('.tablaEditarAgregarPloteo').append(tabla);
                }
                
                /* LIMPIEZA DEL INPUT DESPUES DE AGREGAR LOS METROS */
                $('input[name=editarMetrosPloteo]').val('');
                editarCalculosMetrosPloteo()
            });
            
            $(document).on('keyup', '.tablaEditarAgregarPloteo input.editarMetrosTotalPloteo', function () {
                
                /* OBTENER EL VALOR DEL INPUT */
                let metros = $(this).val();
                // alert(metros)
                
                /* CALCULOS */
                let importe = (metros * 1.25).toFixed(2)
                
                /* IMPRESION EN EL INPUT READONLY DE LA COLUMNA DE IMPORTES */
                $(this).closest('tr').find('td:eq(1)').children('input').val(importe)
                editarCalculosMetrosPloteo()
            })
            /* ELIMINACION INDIVIDUAL DE LOS METROS CUANDO LA TABLA YA ESTA CREADA */
            $(document).on('click', '#eliminarMetros', function () {
                $(this).closest('tr').remove()
                editarCalculosMetrosPloteo()
            })
            
            
            let nuevometro = []
            $(document).on('click', '#eliminarMetros', function () {
                
                nuevometro.push($(this).val())
                console.log(nuevometro)
            })
            
            $('#modalEditarOtPloteo').modal('show');
            
        }
    })
    
})

A continuación subo un video de lo que me sucede cuando cambio de modales.

Video del fallo en los modales y en los arrays

let data = {
    "respuesta": "success",
    "post": [
        {
            "ID_OTPloteo": "61",
            "ID_Cliente": "3",
            "ID_Documento": "2",
            "Subtotal_OTPloteo": "23.75",
            "Impuesto_OTPloteo": "2.85",
            "Total_OTPloteo": "26.60",
            "NumeroDocumento_OTPloteo": "000140",
            "Serie_OTPloteo": "001",
            "Fecha_OTPloteo": "2020-08-19 21:45:12",
            "Nombre_Cliente": "David Alejandro",
            "Apellido_Cliente": "Paucar Briones",
            "Telefono_Cliente": "0992896820",
            "Nombre_Documento": "Factura",
            "Impuesto_Documento": "12",
            "Cantidad_Documento": "141",
            "Serie_Documento": "001",
            "ID_DetalleOTPloteo": "30",
            "Precio_OTPloteo": "3.00",
            "Importe_OTPloteo": "3.75"
        },
        [
            {
                "ID_DetalleOTPloteo": "30",
                "ID_OTPloteo": "61",
                "Precio_OTPloteo": "3.00",
                "Importe_OTPloteo": "3.75"
            },
            {
                "ID_DetalleOTPloteo": "31",
                "ID_OTPloteo": "61",
                "Precio_OTPloteo": "7.00",
                "Importe_OTPloteo": "8.75"
            },
            {
                "ID_DetalleOTPloteo": "32",
                "ID_OTPloteo": "61",
                "Precio_OTPloteo": "9.00",
                "Importe_OTPloteo": "11.25"
            }
        ]
    ]
}

// Recorre los datos
data.post[1].forEach(item => {
    // Crea contenido HTML de la fila
    // Agrega un campo oculto para saber qué es lo que se está modificando
    let html = `<tr>
        <td>
            <input type="hidden" name="idPloteo[]" value="${item.ID_DetalleOTPloteo}">
            <input type="text" name="metrosTotalPloteo[]" class="metrosTotalPloteo form-control" value="${item.Precio_OTPloteo}">
        </td>
        <td><input type="text" class="form-control importeMetrosPloteo" name="importeMetrosPloteo[]" value="${(item.Importe_OTPloteo)}" readonly></td>
        <td><a href="#" value="" class="btn btn-danger btn-icon eliminarMetros" type="button"><i class="icon-trash">Borrar</i></a></td>
    </tr>`;
    // Agrega fila a la tabla
    $('.tablaEditarAgregarPloteo').append(html);
});


$(document).on('click', '.eliminarMetros', function () {
    // Obtener fila a la que pertenece el botón
    let tr = $(this).closest('tr');
        // Eliminar fila y volver a calcular
        $(tr).remove();
        // calculosMetrosPloteo();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


<table class="table table-bordered tablaEditarAgregarPloteo">
                                <thead>
                                    <tr>
                                        <th>Metros</th>
                                        <th>Precio Final</th>
                                        <th>Acción</th>
                                    </tr>
                                </thead>
                                <tbody>
                                
                                </tbody>
                            </table>

2
  • Puedes incluir el codigo del modal con su respectivo script? el 23 ago. 2020 a las 2:51
  • @PauloUrbanoRivera listo ya subi mi codigo el 23 ago. 2020 a las 2:56

1 respuesta 1

1

Quizás deberías crear un arreglo y luego, antes de eliminar la fila, agregar esta sentencia:

arreglo.push(tr.children().first().children()[0].value);

Al terminar, el arreglo contendrá todos los id deseados.

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.