Roly
Roly

Reputation: 161

DataTables: Change value of selected cell using JQuery

I have a DataTable that I fill in from database. I'd like to change the value of the selected cell.

I don't know how to change cell's value by using the cell and row index. How can I do that?

this is what I have:

  $('#dtBasicExample').on('click', 'tbody td', function() {

  var table = $('#dtBasicExample').DataTable();

  //Content I want to insert i the cell
  var NewValue= 'NewValue';

  //get cell index
  var CellIndex=table.cell( this ).index().columnVisible;

  //get row index
  var RowIndex= table.cell( this ).index().row;
})

Upvotes: 0

Views: 16078

Answers (2)

mike85
mike85

Reputation: 631

With demo:

$('#example').on('click', 'td', function() {
  var table = $(this).closest('table').DataTable();
  table.cell(this).data("new");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css" rel="stylesheet" />

<p>Click any cell and check how we simply change it</p>

<table id="example" class="display" style="width:100%">
  <thead>
    <tr>
      <th>Name</th>
      <th>Position</th>
      <th>Office</th>
      <th>Numero</th>
      <th>Start date</th>
      <th>Salary</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Tiger Nixon</td>
      <td>System Architect</td>
      <td>Edinburgh</td>
      <td>155555</td>
      <td>2011/04/25</td>
      <td>$320,800</td>
    </tr>
    <tr>
      <td>Garrett Winters</td>
      <td>Accountant</td>
      <td>Tokyo</td>
      <td>63</td>
      <td>2011/07/25</td>
      <td>$170,750</td>
    </tr>
    <tr>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>1</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
  </tbody>
  <tfoot>
    <tr>
      <td>Ashton Cox</td>
      <td>Junior Technical Author</td>
      <td>San Francisco</td>
      <td>1</td>
      <td>2009/01/12</td>
      <td>$86,000</td>
    </tr>
  </tfoot>
</table>

Upvotes: 2

hiltononline
hiltononline

Reputation: 536

To change the data in a cell, you need the cell().data() function from the DataTables API: https://datatables.net/reference/api/cell().data()

$(document).ready(function() {
  var table = $('#example').DataTable();
  $('#example tbody').on('click', 'td', function() {
    var colIndex = table.cell(this).index().column;
    var rowIndex = table.cell(this).index().row;
    table.cell(rowIndex, colIndex).data("new")
  });
});

A simpler approach:

$(document).ready(function() {
  var table = $('#example').DataTable();
  $('#example tbody').on('click', 'td', function() {
     table.cell(this).data("new");
   });
});

Upvotes: 3

Related Questions