Crear otra datatable a partir de tabla ya creada

Crear otra datatable a partir de tabla ya creada

Lucaslopez12Lucaslopez12 Posts: 14Questions: 6Answers: 0
edited January 21 in DataTables

Tengo una tabla creada con datatable, quiero que al hacer click en un boton o el nombre del campo de productos me renderize otra tabla nueva con solamente los modelos de ese producto. Lo intenté con html .createlemnt y javascript pero no logro conseguir lo que quiero, al ser datatables se me complica por que no es lo mismo que renderizar tablas con html puro. Mi código es el siguiente:

HTML:

 <table id="sellersQuantityTable" class="table table-bordered table-striped table-sm">
                    <thead class="text-center">
                      <tr>
                        <td>MARCA</td>
                        <td>MODELO</td>
                        <td>CANTIDAD</td>
                      </tr>
                    </thead>
                    <tbody class="text-center">

                    </tbody>
                  </table>

Javascript:

const tableRanking = $("#sellersQuantityTable").DataTable({
dom: 'Pfrtip',
responsive: true, "lengthChange": false, "autoWidth": false, "searching": true, fixedHeader: true, "scrollX": true,
buttons: [
    {
    extend: "excel",
    title: '',
    filename: 'Venta por Financiera',
    exportOptions: { orthogonal: 'export' },
    
}],

language: {
    "url": "//cdn.datatables.net/plug-ins/1.10.24/i18n/Spanish.json"
},
columns: [
    { "data": "MARCA" },
    { "data": "MODELO" },
    {
        "data": "Monto", render: function (data, type, row) {
            return type === 'export' ?
                data.replaceAll(/[$ |.]/g, '').replace(',', '.') :
                data;
        }
    }, 
],
order: [[1, "desc"]],
rowsGroup: [0]
});

Esta es mi tabla:

Lo que quiero lograr es que al hacer click en el campo de producto me cree una nueva tabla con solamente el modelo de ese producto y la cantidad

Busqué en google y todos los lugares que conozco pero no encontré nada parecido. Se me hace algo complicado a mi parecer- Muchas gracias.

Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 15,760Questions: 25Answers: 3,736

    This example shows how to create click event handlers and get the row data of the clicked row. The data can then be used to create an HTML table or Datatable.

    Kevin

  • Lucaslopez12Lucaslopez12 Posts: 14Questions: 6Answers: 0

    Thanks Kevin. It works but i dont know how create other table. It can be used HTML createElement in this DataTable?

    Or how would you?

  • kthorngrenkthorngren Posts: 15,760Questions: 25Answers: 3,736

    What I want to achieve is that when I click on the product field, I create a new table with only the model of that product and the quantity

    Do you want to create a new HTML table on the same page or a new Datatalbe on the same page?

    You can search for tutorials to use Javascript to dynamically create new tables.

    This example shows how to create a Datatable with Javascript data, data from the click event for example. Click the HTML tab and you will see that all Datatables needs is a table element and the example uses columns.title to create the headers.

    Kevin

  • Lucaslopez12Lucaslopez12 Posts: 14Questions: 6Answers: 0
    edited January 21

    Thanks!

    $(document).ready(function() {
        var table = $('#sellersQuantityTable').DataTable();
         
        $('#sellersQuantityTable tbody').on('click', 'tr', function () {
            var dataNew = table.row( this ).data();
            console.log(dataNew);
        } );
    

    With this I can get the data in a json from where I click, but I can't send it to the new table. What am I doing wrong?

    My new table:

    $(document).ready(function() {
        $('#example2').DataTable( {
            data: dataNew,
            columns: [
                { title: "Name" },
                { title: "Position" },
                { title: "Office" },
                { title: "Extn." },
                { title: "Start date" },
                { title: "Salary" }
            ]
        } );
    } )
    

    In HTML:

           <table id="example2" class="display" width="100%"></table>
    

    Edited by Kevin: Syntax highlighting. Details on how to highlight code using markdown can be found in this guide

  • kthorngrenkthorngren Posts: 15,760Questions: 25Answers: 3,736
    edited January 21 Answer ✓

    Use the triple back ticks as on new lines as described below the Post Comment button to format blocks of code.

    Looks like you are initializing the Datatable before you want to add the data. So instead of using data to load the data you can remove data: dataNew, and initialize an empty Datatable.

    In the click event you can use clear() followed by row.add() to clear then add the rows to the Datatable. Something like this:

        $('#sellersQuantityTable tbody').on('click', 'tr', function () {
            var dataNew = table.row( this ).data();
    
            var table2 = $('#example2').DataTable();
            table2.clear();
            table2.row.add( dataNew ).draw();
        } );
    

    You will need to define columns.data to match your source data (newData) data structure.

    Kevin

Sign In or Register to comment.