3

I am working with and I want to edit and delete data table records

When I do console.log(row) following output I get:

["user1", "Edit"] (index):274 (2) ["user2", "Edit"] (index):274 (2) ["user3", "Edit"] (index):274 (2) ["user4", "Edit"] (index):274 (2) ["user5", "Edit"]

What I want is to get data-id from render: function (data, type, row) which I have used in datatable script and when click on edit button I want to get specific id in alert but I am unable to extract data-id.

My jQuery code:

$.fn.dataTable.ext.errMode = 'none';
var table = $('#catgeory_list').DataTable({
        processing: true,
        language: {
            emptyTable: 'no result found.'
        },
        columnDefs: [{
                visible: true,
                targets: 0,
                render: function (data, type, full, meta) {
                    return data;
                }
            }, {
                visible: true,
                targets: 1,
                render: function (data, type, row) {
                    console.log(row);
                    return '<button id="editBtn" class="btn btn-wrang btn-flat edit" name="editBtn" type="button">Edit</button>' + '&nbsp;&nbsp;<button id="deleteBtn" class="btn btn-danger btn-flat delete" name="deleteBtn" type="button" >Delete</button>';
                }
            }
        ],
    });
1
  • 1
    Just few suggestions, regarding your code: render option doesn't seem to do anything for your first column, so may be skipped; formatting padding around buttons with &nbsp doesn't seem to be a good practice, you may use CSS for that purpose (e.g., like I did in my answer below) Commented Aug 5, 2019 at 8:42

2 Answers 2

2

In order to get any source object/array property/item for the row being clicked, you don't need anything more than simple row().data() API method invoked against DataTable row (selected by the closest to the clicked button <tr> node):

$('table').on('click', 'tbody td button', function(){
  const rowData = dataTable.row($(this).closest('tr')).data();
  alert(`Row ID is ${rowData.id}`);
});

Here, dataTable is a variable, you assign your DataTable to.

Full-blown DEMO you might find below.

Also, considering your ultimate goal, you might find of use my answer over here, which provides complete working demo of editable DataTable. So, if you find that helpful, upvotes are appreciated ;)

//src data
const srcData = [
  {id: 1, item: 'apple'},
  {id: 2, item: 'banana'},
  {id: 3, item: 'tomato'}
];

//datatables init
const dataTable = $('table').DataTable({
  dom: 't',
  data: srcData,
  columns: [{data: 'item', title: 'Item Name', render: data => data+'<button>Show Id</button>'}]
});

//click handler
$('table').on('click', 'tbody td button', function(){
  const rowData = dataTable.row($(this).closest('tr')).data();
  alert(`Row ID is ${rowData.id}`);
});
td button {float: right}
<!doctype html><html><head><link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.css" /><script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script><script type="text/javascript" src="https://cdn.datatables.net/v/dt/jq-3.3.1/dt-1.10.18/rg-1.1.0/datatables.min.js"></script></head><body><table></table></body></html>

Sign up to request clarification or add additional context in comments.

2 Comments

Whats if : "Uncaught ReferenceError: dataTable is not defined" ?
Then you have a different name (if any at all) for a variable you assign 'DataTable()' constrictor output to.
1

You can wrap data or row parameter from callback function with jQuery $() to get any element/node attributes or DOM manipuation. Refer also toJQuery() for dealing with Datatables API instances.

Render

render: function(data, type, row, meta){
                    var data_id = $(data).data('id');
                    console.log('Columns.Render:',data_id);
                    return data + " : data-id(" + data_id+")";
            }

createdRow

createdRow: function (row, data, index) {
                    var data_id = $('td a.edit_row', row).data('id');
                    console.log('CreatedRow:',data_id);
        }

Click Event

$("a.edit_row").click(function(){
        var data_id = $(this).data('id');
        alert(data_id);
      });

Working Live Demo:

$(document).ready( function () {
  var table = $('#example').DataTable({
    
    columnDefs: [
      {
        targets: 1,
        render: function(data, type, row, meta){
                var data_id = $(data).data('id');
                console.log('Columns.Render:',data_id);
                return data + " : data-id(" + data_id+")";
        }
      },
    ],
    createdRow: function (row, data, index) {
                var data_id = $('td a.edit_row', row).data('id');
                console.log('CreatedRow:',data_id);
    }

  });
  
  
  $("a.edit_row").click(function(){
    var data_id = $(this).data('id');
    alert(data_id);
  });
} );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <link href="https://nightly.datatables.net/css/jquery.dataTables.css" 

rel="stylesheet" type="text/css" />
    <script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
    
    <table id="example" class="display nowrap" width="100%">
        <thead>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
          </tr>
        </thead>

        <tfoot>
          <tr>
            <th>Name</th>
            <th>Position</th>
            <th>Office</th>
            <th>Age</th>
            <th>Start date</th>
            <th>Salary</th>
          </tr>
        </tfoot>

        <tbody>
          <tr>
            <td>Tiger Nixon</td>
            <td><a href="javascript:void(0)" class="edit_row" data-id="2">Edit</a></td>
            <td>Edinburgh</td>
            <td>61</td>
            <td>2011/04/25</td>
            <td>$3,120</td>
          </tr>
          <tr>
            <td>Garrett Winters</td>
            <td><a href="javascript:void(0)" class="edit_row" data-id="3">Edit</a></td>
            <td>Edinburgh</td>
            <td>63</td>
            <td>2011/07/25</td>
            <td>$5,300</td>
          </tr>
          <tr>
            <td>Ashton Cox</td>
            <td><a href="javascript:void(0)" class="edit_row" data-id="4">Edit</a></td>
            <td>San Francisco</td>
            <td>66</td>
            <td>2009/01/12</td>
            <td>$4,800</td>
          </tr>
        </tbody>
      </table>

1 Comment

This works but you would be going around datatables adding extra unnecessary layers on top when the information is extracable from datatables without this, see Yevgen Gorbunkov' answer to do this working with dattables

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.