Search code examples
htmljqueryhtml-tabledatatabledatatables

DataTable add a button to each row


Using DataTable API, I am creating a table & adding a button - 'Click' to each table row. Example link below:

https://datatables.net/examples/ajax/null_data_source.html

On the click I am changing text to 'View'. So, after page reload, rather all the buttons displaying default text - 'Click', how to render some buttons with text - 'Click' while the others which were clicked with - 'View'. Experts please share your inputs!!

$(document).ready(function() {
    var table = $('#example').DataTable( {
      "ajax": {
          "type": "get",
          "url": "https://jsonplaceholder.typicode.com/todos",            
          "dataType": "json",
          "dataSrc": function (json) {
                 var return_data = new Array();
                 for (var i = 0; i < json.length; i++) {
                     return_data.push({
                         'userId': json[i].userId,
                         'id': json[i].id,
                         'title': "Test Data"
                     })
                 }
                 return return_data;
          }
      },
      "columns": [
             { 'data': 'userId' },             
             { 'data': 'id' },
             { 'data': 'title' },
             { 'data': null }
        ],
       "columnDefs": [
         { targets: 0, className: 'dt-body-center'},
         { targets: 1, className: 'dt-body-center'},
         { targets: 2, className: 'dt-body-center'},
         { targets: -1, width: "150px", 
           className: 'dt-body-center', defaultContent:         
           "<button id='btnDetails'>Click</buttom>" }
        ]});

  $('#example tbody').on('click', '[id*=btnDetails]', function () {
       $(this).text("View");
  });  
});
<html>

<head>
    <meta charset='utf-8'>
    <meta http-equiv='X-UA-Compatible' content='IE=edge'>        
    <meta name='viewport' content='width=device-width, initial-scale=1'>
  <link href="https://cdn.datatables.net/1.11.3/css/jquery.dataTables.min.css"  rel="stylesheet">
  <script      src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js">    </script>
 <script src="https://cdn.datatables.net/1.11.3/js/jquery.dataTables.min.js">  </script>
  </head>
  <body>
  <table id="example" class="display cell-border compact stripe"    style="width:100%">
        <thead>
            <tr>
                <th>User Id</th>
                <th>Id</th>
                <th>Title</th> 
                <th>Status</th>
            </tr>
        </thead>
  </table>
  </body>
</html>


Solution

  • You need a database to persist the state of button. Check below link for server-side processing:

    https://datatables.net/examples/data_sources/server_side.html