3

can anyone help me on how to get a single row data on a click event.

This is the table which is dynamically populated after Success function in AJAX call is executed

<div class="table-responsive table-wrap tableFixHead container-fluid">
<table class="table bg-violet dT-contain" id="datatable" >
    <thead class="thead-dark">
        <tr>
            <th>No.</th>
            <th>Main</th>
            <th>Shrinked</th>
            <th>Clicks</th>
            <th>Disable</th>
            <th>Delete</th>
        </tr>
    </thead>
    <tbody>
        <tr class="bg-violet">

        </tr>
    </tbody>
</table>
</div>

<script src="scripts/jquery-3.5.1.min.js"></script>
<script src="scripts/jquery.dataTables.min.js"></script>
<script src="scripts/dataTables.bootstrap4.min.js" defer></script>
<script src="scripts/dashboard.js" defer></script>

This is my ajax success function

success: function(data){
        $('#datatable').dataTable({
        data: data,
        "autoWidth": true,
        columns: [
            {'data': 'id'},
            {'data': 'main'},
            {'data': 'shrinked'},
            {'data': 'clicks'},
            {"defaultContent": "<button id='del-btn'>Delete</button>"}
            ]
        })
    }

I am adding a delete button to each row dynamically, but can't seem to fetch row data using it. I tried this method with some tweaks to my success function

$('#datatable tbody').on( 'click', 'button', function () {
    var data = table.row( $(this).parents('tr') ).data();
    alert( data[0] );
} );

But this didn't seem to work.

The JSON data returning from the AJAX call is in this format:

[{"id":"12","main":"ndkekfnq" ...}, {.....}]

I also added an onclick function on the delete button to try to fetch data but that also didn't work.

EDIT: whole AJAX request

$(document).ready(()=>{
$.ajax({
    url: 'URL',
    method: 'post',
    dataType: 'json',
    data: {
        "email": window.email,
        "token": window.token
    },
    success: function(data){
        let table = $('#datatable').dataTable({
        data: data,
        "autoWidth": true,
        columns: [
                {'data': 'id'},
                {'data': 'main'},
                {'data': 'shrinked'},
                {'data': 'clicks'},
                {"defaultContent": "<button id='dis-btn' class='btn btn-warning'>Disable</button>"},
                {"defaultContent": "<button id='del-btn' class='btn btn-danger'>Delete</button>"}
            ]
        })
        $('#datatable tbody').on('click', "#del-btn", function() {
            let row = $(this).parents('tr')[0];
            //for row data
            console.log(table.row(row).data().id);
        });
    }
})

})

What would be the correct way to do this? Thank you

2
  • Can you provide a minimal reproducible example ? This is not enough on what you have posted. Commented Aug 4, 2020 at 2:49
  • Added more content in the body... Commented Aug 4, 2020 at 3:20

3 Answers 3

4

You need to use column.render instead o defaultContent and then get the data on an outside function, you need to render a button at the render of the table:

    <!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <link
      rel="stylesheet"
      href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.min.css"
    />
    <script src="https://code.jquery.com/jquery-3.5.1.js"></script>
    <script src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.min.js"></script>
  </head>
  <body>
    <div class="table-responsive table-wrap tableFixHead container-fluid">
        <table class="table bg-violet dT-contain" id="datatable" >
            <thead class="thead-dark">
                <tr>
                    <th>No.</th>
                    <th>Main</th>
                    <th>Shrinked</th>
                    <th>Clicks</th>
                    <th>Delete</th>
                </tr>
            </thead>
            <tbody>
                <tr class="bg-violet">
        
                </tr>
            </tbody>
        </table>
    <script>
      $('#datatable').dataTable( {
            "data": [{'id':20,'main':'hola','shrinked':false,'clicks':2000},{'id':21,'main':'hola','shrinked':false,'clicks':283000}],
            "autoWidth": true,
            "columns": [ 
                {"data": "id"},        
                {'data': 'main'},
                {'data': 'shrinked'},
                {'data': 'clicks'},
                {"data": "id",
                    "render": function ( data, type, row, meta ) { 
                        return '<button data-id="'+data+'" onclick="deleteThis(event)">Delete</button>'
                        }
                }
                
             ]
        } )

function deleteThis(e){
  console.log(e.target.getAttribute('data-id'))
}
    </script>
  </body>
</html>

Haven't tried, but based on Datatables docs, this should work, let me know if it worked.

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

Comments

2

Here is working code for you. You need to set the datatables in a var.

Use that var table to look for clicked row which will $(this).parents('tr')[0] and use .data.id to the clicked item id

I have recreated the your example and its working fine. Just set you ajax response to the data.

Demo

//Ajax Data
var data = [{
  "id": "10",
  "main": "ndkekfnq",
  "shrinked": "ndkekfnq",
  "clicks": "ndkekfnq"
}, {
  "id": "12",
  "main": "Something",
  "shrinked": "Data",
  "clicks": "Ha"
}]

//Data Table
var table = $('#datatable').DataTable({
  data: data,
  columns: [{
      'data': 'id'
    },
    {
      'data': 'main'
    },
    {
      'data': 'shrinked'
    },
    {
      'data': 'clicks'
    },
    {
      "defaultContent": "<button id='del-btn'>Delete</button>"
    }
  ]
});


$('#datatable tbody').on('click', "#del-btn", function() {
  var row = $(this).parents('tr')[0];
  //for row data
  console.log(table.row(row).data().id);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/js/jquery.dataTables.min.js" integrity="sha512-BkpSL20WETFylMrcirBahHfSnY++H2O1W+UnEEO4yNIl+jI2+zowyoGJpbtk6bx97fBXf++WJHSSK2MV4ghPcg==" crossorigin="anonymous"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/datatables/1.10.21/css/jquery.dataTables.min.css" integrity="sha512-1k7mWiTNoyx2XtmI96o+hdjP8nn0f3Z2N4oF/9ZZRgijyV4omsKOXEnqL1gKQNPy2MTSP9rIEWGcH/CInulptA==" crossorigin="anonymous" />
<div class="table-responsive table-wrap tableFixHead container-fluid">
  <table class="table bg-violet dT-contain" id="datatable">
    <thead class="thead-dark">
      <tr>
        <th>No.</th>
        <th>Main</th>
        <th>Shrinked</th>
        <th>Clicks</th>
        <th>Delete</th>
      </tr>
    </thead>
    <tbody>
      <tr class="bg-violet">

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

7 Comments

Thank you very much, but i dont wanna remove the row but rather access the "id" property of the row in which the button has been clicked, any idea how to do that?
I tried, but still can't get to log or alert the id, the console.log('working') inside the delete function is working fine, but data is not being logged
@ZulfiqarAli How come its working in the snippet above As soon as i click on delete i am getting the id of the row ? Can you make sure you are using the exact code i have provided. Let me know
@ZulfiqarAli Can you make sure copy the exact code and Data-tables function with a var table = $('#datatable').DataTable({})
I have updated my original post with whole AJAX request, i am sure i am doing everything as you suggested but still its not logging the response
|
2

@Javier 's answer is a very good way to solve the OP's issue. Another way, if you don't want to include id field twice, would be like this:

"columns": [ 
            {"data": "id"},        
            {'data': 'main'},
            {'data': 'shrinked'},
            {'data': 'clicks'},
            {"data": null,
                "render": function ( data, type, row, meta ) { 
                    return '<button data-id="' + data.id + '" onclick="deleteThis(event)">Delete</button>'
                    }
            }
         ]

2 Comments

Yeah good advice, keeps the code dry i guess. Thank you.
@ZulfiqarAli another advantage of this approach is that now with data you have access to any field in the render property, while if you specify a field in the data property, data will have access to that field only.

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.