How do I add button on each row in datatable?

JavascriptJqueryDatatables

Javascript Problem Overview


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",
        ""
    ]
]
 }

Javascript Solutions


Solution 1 - Javascript

Basically your code is okay, thats the right way to do this. Anyhow, there are some misunderstandings:

  1. fetchUserData.cfm does not contain key/value pairs. So it doesn't make sense to address keys in mData. Just use mData[index]

  2. dataTables expects some more info from your serverside. At least you should tell datatables how many items in total are on your serverside and how many are filtered. I just hardcoded this info to your data. You should get the right values from counts in your server sided script.

     {
      "iTotalRecords":"6",
      "iTotalDisplayRecords":"6",
       "aaData": [
     [
     	"1",
     	"sameek",
     	"sam",
     	"sam",
     	"[email protected]",
     	"1",
     	""
     ],...
    
  3. If you have the column names already set in the html part, you don't need to add sTitle.

  4. The mRender Function takes three parameters:

  • data = The data for this cell, as defined in mData
  • type = The datatype (can be ignored mostly)
  • full = The full data array for this row.

So your mRender function should look like this:

  "mRender": function(data, type, full) {
    return '<a class="btn btn-info btn-sm" href=#/' + full[0] + '>' + 'Edit' + '</a>';
  }

Find a working Plunker here

Solution 2 - Javascript

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;
			}},
    ],
	}
}

Solution 3 - Javascript

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 ] );
    } );
} );

Solution 4 - Javascript

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

Solution 5 - Javascript

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'           
        });       
    });

Solution 6 - Javascript

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(); }

Solution 7 - Javascript

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!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSameek MishraView Question on Stackoverflow
Solution 1 - JavascriptmainguyView Answer on Stackoverflow
Solution 2 - JavascriptMajid RamzaniView Answer on Stackoverflow
Solution 3 - Javascriptplassede senraView Answer on Stackoverflow
Solution 4 - Javascriptuser2341112View Answer on Stackoverflow
Solution 5 - JavascriptMd. Didarul IslamView Answer on Stackoverflow
Solution 6 - JavascriptRolandoView Answer on Stackoverflow
Solution 7 - JavascriptKimJangHunView Answer on Stackoverflow