[javascript] How do I add button on each row in datatable?

I am newbie for DataTables. I want to add button on each row for edit and delete(like below image)

enter image description here

I have tried with code:

Test.cfm

<table id="myDataTable" class="table table-striped table-bordered">
<thead>
    <tr>
        <th>UserID</th>
        <th>Name</th>
        <th>UserName</th>
        <th>Passowrd</th>
        <th>Email</th>
         <th>IsActive</th>
         <th>Command</th>
    </tr>
</thead>
<tbody> 
</tbody>

$(document).ready(function () {
    var oTable = $('#myDataTable').dataTable({
       // "bServerSide": true,
        "sAjaxSource": "fetchUserData.cfm",
        "bProcessing": true,
        "sPaginationType": "full_numbers",
        "aoColumns": [
            { "mData": null },
            { "mData": "Name", "sTitle": "Name" , "sWidth": "20%"},
            { "mData": "UserName", "sTitle": "UserName", "sWidth": "20%" },
            { "mData": "Passowrd","sTitle": "Passowrd", "sWidth": "20%"  },
            { "mData": "Email","sTitle": "Email"  , "sWidth": "20%"},
            { "mData": "IsActive","sTitle": "IsActive" , "sWidth": "20%" },
            {
                "mData": null,
                "bSortable": false,
               "mRender": function (o) { return '<a href=#/' + o.userid + '>' + 'Edit' + '</a>'; }
            }
        ]
    });

} );

fetchUserData.cfm

{
"aaData": [
    [
        "1",
        "sameek",
        "sam",
        "sam",
        "[email protected]",
        "1",
        ""
    ],
    [
        "2",
        "arun singh",
        "arun",
        "arun",
        "[email protected]",
        "0",
        ""
    ],
    [
        "9",
        "s s",
        "sam3",
        "sam3",
        "[email protected]",
        "0",
        ""
    ],
    [
        "10",
        "sameek mishra",
        "sam56",
        "sam",
        "[email protected]",
        "0",
        ""
    ],
    [
        "11",
        "narendra kumar",
        "narendra",
        "nav",
        "[email protected]",
        "1",
        ""
    ],
    [
        "12",
        "test test",
        "test",
        "test",
        "[email protected]",
        "1",
        ""
    ]
]
 }

This question is related to javascript jquery datatables

The answer is


my recipe:

datatable declaration:

defaultContent: "<button type='button'....

events:

$('#usersDataTable tbody').on( 'click', '.delete-user-btn', function () { var user_data = table.row( $(this).parents('tr') ).data(); }

var table =$('#example').DataTable( {
    data: yourdata ,
    columns: [
        { data: "id" },
        { data: "name" },
        { data: "parent" },
        { data: "date" },

        {data: "id" , render : function ( data, type, row, meta ) {
              return type === 'display'  ?
                '<a href="<?php echo $delete_url;?>'+ data +'" ><i class="fe fe-delete"></i></a>' :
                data;
            }},
    ],
    }
}

I contribute with my settings for buttons: view, edit and delete. The last column has data: null At the end with the property defaultContent is added a string that HTML code. And since it is the last column, it is indicated with index -1 by means of the targets property when indicating the columns.

//...
columns: [
    { title: "", "data": null, defaultContent: '' }, //Si pone da error al cambiar de paginas la columna index con numero de fila
    { title: "Id", "data": "id", defaultContent: '', "visible":false },
    { title: "Nombre", "data": "nombre" },
    { title: "Apellido", "data": "apellido" },
    { title: "Documento", "data": "tipo_documento.siglas" },
    { title: "Numero", "data": "numero_documento" },
    { title: "Fec.Nac.", format: 'dd/mm/yyyy', "data": "fecha_nacimiento"}, //formato
    { title: "Teléfono", "data": "telefono1" },
    { title: "Email", "data": "email1" }
    , { title: "", "data": null }
],
columnDefs: [
    {
        "searchable": false,
        "orderable": false,
        "targets": 0
    },
    { 
      width: '3%', 
      targets: 0  //la primer columna tendra una anchura del  20% de la tabla
    },
    {
        targets: -1, //-1 es la ultima columna y 0 la primera
        data: null,
        defaultContent: '<div class="btn-group"> <button type="button" class="btn btn-info btn-xs dt-view" style="margin-right:16px;"><span class="glyphicon glyphicon-eye-open glyphicon-info-sign" aria-hidden="true"></span></button>  <button type="button" class="btn btn-primary btn-xs dt-edit" style="margin-right:16px;"><span class="glyphicon glyphicon-pencil" aria-hidden="true"></span></button><button type="button" class="btn btn-danger btn-xs dt-delete"><span class="glyphicon glyphicon-remove glyphicon-trash" aria-hidden="true"></span></button></div>'
    },
    { orderable: false, searchable: false, targets: -1 } //Ultima columna no ordenable para botones
], 
//...

enter image description here


well, i just added button in data. For Example, i should code like this:

$(target).DataTable().row.add(message).draw()

And, in message, i added button like this : [blah, blah ... "<button>Click!</button>"] and.. it works!


take a look here... this was very helpfull to me https://datatables.net/examples/ajax/null_data_source.html

$(document).ready(function() {
    var table = $('#example').DataTable( {
        "ajax": "data/arrays.txt",
        "columnDefs": [ {
        "targets": -1,
        "data": null,
        "defaultContent": "<button>Click!</button>"
    } ]
} );

$('#example tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] +"'s salary is: "+ data[ 5 ] );
    } );
} );

Take a Look.

$(document).ready(function () {     
        $('#datatable').DataTable({
            columns: [
                { 'data': 'ID' },
                { 'data': 'AuthorName' },
                { 'data': 'TotalBook' },
                { 'data': 'DateofBirth' },
                { 'data': 'OccupationEN' },   
                { 'data': null, title: 'Action', wrap: true, "render": function (item) { return '<div class="btn-group"> <button type="button" onclick="set_value(' + item.ID + ')" value="0" class="btn btn-warning" data-toggle="modal" data-target="#myModal">View</button></div>' } },
            ],            
            bServerSide: true,
            sAjaxSource: 'EmployeeDataHandler.ashx'           
        });       
    });

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to datatables

Datatables Select All Checkbox DataTables: Cannot read property style of undefined How do I filter date range in DataTables? DataTables: Cannot read property 'length' of undefined TypeError: $(...).DataTable is not a function jQuery DataTables Getting selected row values How to manually update datatables table with new JSON data DataTables: Uncaught TypeError: Cannot read property 'defaults' of undefined How to redraw DataTable with new data Datatables: Cannot read property 'mData' of undefined