0

tengo una duda con respecto de como hacer que el DataTable detecte que hay información en mi tabla.

En mi tabla yo no tengo nada en el tbody, ya que tengo unos input y con javascript lo que vaya poniendo en ellos mediante un botón la información se agrega a la tabla, ¿Cómo podría hacer que me detecte que hay contenido en la tabla?

Este es mi código de html donde se encuentra la tabla:

        <table class="lists" id="lists">
        <tr>
            <td>
                <form onsubmit="event.preventDefault();onFormSubmit();" autocomplete="off">
                    <div>
                        <label>Nota*</label><label class="validation-error hide" id="fullNameValidationError">Este dato es requerido</label>
                        <input type="text" name="nota" id="nota">
                    </div>
                    <div>
                        <label>Etiqueta</label>
                        <input type="text" placeholder="#" name="etiqueta" id="etiqueta">
                    </div>
                    <div  class="form-action-buttons">
                        <input type="submit" value="Agregar">
                    </div>
                </form>
            </td>
            <td>
                <table class="list" id="myTable">
                    <thead>
                        <tr>
                            <th>Nota</th>
                            <th>Etiqueta</th>
                            <th></th>
                        </tr>
                    </thead>

                    <tbody>
                     
                    </tbody>
                </table>
            </td>
        </tr>
    </table>

Este es el código de javascript para que la tabla se vaya llenando:

    var selectedRow = null

function onFormSubmit() {
    if (validate()) {
        var formData = readFormData();
        if (selectedRow == null)
            insertNewRecord(formData);
        else
            updateRecord(formData);
        resetForm();
    }
}

function readFormData() {
    var formData = {};
    formData["nota"] = document.getElementById("nota").value;
    formData["etiqueta"] = document.getElementById("etiqueta").value;
    return formData;
}

function insertNewRecord(data) {
    var table = document.getElementById("myTable").getElementsByTagName('tbody')[0];
    var newRow = table.insertRow(table.length);
    cell1 = newRow.insertCell(0);
    cell1.innerHTML = data.nota;
    cell2 = newRow.insertCell(1);
    cell2.innerHTML = data.etiqueta;
    cell2 = newRow.insertCell(2);
    cell2.innerHTML = `<a onClick="onEdit(this)">Editar</a>
                       <a onClick="onDelete(this)">Eliminar</a>`;
}

function resetForm() {
    document.getElementById("nota").value = "";
    document.getElementById("etiqueta").value = "";
    selectedRow = null;
}

function onEdit(td) {
    selectedRow = td.parentElement.parentElement;
    document.getElementById("nota").value = selectedRow.cells[0].innerHTML;
    document.getElementById("etiqueta").value = selectedRow.cells[1].innerHTML;
}
function updateRecord(formData) {
    selectedRow.cells[0].innerHTML = formData.nota;
    selectedRow.cells[1].innerHTML = formData.etiqueta;
}

function onDelete(td) {
    if (confirm('¿Esta seguro de eliminar esta nota?')) {
        row = td.parentElement.parentElement;
        document.getElementById("myTable").deleteRow(row.rowIndex);
        resetForm();
    }
}
function validate() {
    isValid = true;
    if (document.getElementById("nota").value == "") {
        isValid = false;
        document.getElementById("fullNameValidationError").classList.remove("hide");
    } else {
        isValid = true;
        if (!document.getElementById("fullNameValidationError").classList.contains("hide"))
            document.getElementById("fullNameValidationError").classList.add("hide");
    }
    return isValid;
}

Y por último este es el código del datatable en javascript:

$(document).ready(function () {
$('#myTable').DataTable({
    language: {
        processing: "Tratamiento en curso...",
        search: "Buscar&nbsp;:",
        lengthMenu: "Agrupar de _MENU_ items",
        info: "Mostrando del item _START_ al _END_ de un total de _TOTAL_ items",
        infoEmpty: "No existen datos.",
        infoFiltered: "(filtrado de _MAX_ elementos en total)",
        infoPostFix: "",
        loadingRecords: "Cargando...",
        zeroRecords: "No se encontraron datos con tu busqueda",
        emptyTable: "No hay datos disponibles en la tabla.",
        paginate: {
            first: "Primero",
            previous: "Anterior",
            next: "Siguiente",
            last: "Ultimo"
        },
        aria: {
            sortAscending: ": active para ordenar la columna en orden ascendente",
            sortDescending: ": active para ordenar la columna en orden descendente"
        }
    },
    scrollY: 400,
    lengthMenu: [ [10, 25, -1], [10, 25, "All"] ],
});

});

Adjunto imagen de como se ve la tabla: introducir la descripción de la imagen aquí

Muchas gracias:)

1
  • Te complicaste bastante. En lugar de trabajar con los atributos de tablas de HTML hubieras trabajado con los de DataTables. Por ejemplo, estás utilizando cell1 = newRow.insertCell(0); en su lugar, habrias utilizado table.row.add( { "Nota": "Ejemplo", "Etiqueta": "5" } ).draw();
    – EvilFearzZ
    el 16 may. 2022 a las 22:10

1 respuesta 1

0

Te dejo un ejemplo de como se emplea row.add

$(document).ready(function() {
  

  var t = $('#myTable').DataTable( {
       
        language: {
        processing:     "Procesando...",
        search:         "Buscar:",
        lengthMenu:     "Mostrando _MENU_ registros",
        info:           "Mostrando registros del <b> _START_ </b> al <b> _END_ </b> de un total de <b> _TOTAL_ </b> registros",
        infoEmpty:      "Mostrando registros del <b>0</b> al <b>0</b> de un total de <b>0</b> registros",
        infoFiltered:   "(filtrado de un total de <b> _MAX_ </b> registros)",
        infoPostFix:    "",
        loadingRecords: "Cargando...",
        zeroRecords:    "No se encontraron registros",
        emptyTable:     "Ningún dato disponible en esta tabla",
        paginate: {
          first:      "Inicio",
          previous:   "<",
          next:       ">",
          last:       "Último"
            },
            aria: {
                sortAscending:  ": Activar para ordenar la columna de manera ascendente",
                sortDescending: ": Activar para ordenar la columna de manera descendente"
            }
        },
        pagingType: "full_numbers"
      });
  
  var counter = 1;

  $('#addRow').on('click', function() {
    var text1 = $("#column1").val();
    var text2 = $("#column2").val();
    var text3 = "Borrar/Editar";
    
    t.row.add([
      text1,
      text2,
      text3
    ]).draw(false);

    counter++;
  });

  // Automatically add a first row of data
  $('#addRow').click();
});
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-1.12.3.js"></script>
<script src="https://cdn.datatables.net/1.10.12/js/jquery.dataTables.min.js"></script>


<button id="addRow">Agregar</button>
<input type="text" id="column1" placeholder="Nota">
<input type="text" id="column2" placeholder="Etiqueta">

<table id="myTable" class="table table-striped  table-bordered" cellspacing="0" width="100%">
    <thead>
        <tr>
            <th>Nota</th>
            <th>Etiqueta</th>
            <th>Accion</th>
        </tr>
    </thead>
</table>

1
  • 1
    Muchas gracias!
    – Sarahi
    el 17 may. 2022 a las 17:22

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.