Question:
How do I get the value of a column that has the visible: false
?
"columns": [
{ data: "Nomes", autoWidth: true, visible: false},
]
Names column example, I'm currently doing this.
$(this).parent().parent().find('td').eq(0).text()
But if I do it this way it doesn't return if the column has visible: false
Answer:
When Datatables are rendered, invisible columns are completely excluded from the DOM, thus being inaccessible via regular JavaScript. It is necessary to use the component API, that is, the row().data() method will return the row data via JSON.
To get the line of the clicked element you use:
var linha = $(this).closest("tr");
The .closest("tr")
will fetch the first parent tr
element of the clicked element.
As the spine is named with the term Nomes
, just pick up the value .data().Nomes
Row of the returned in the variable linha
:
var texto = $('#table_id').DataTable().row(linha).data().Nomes;
The
'#table_id'
selector is the table id. Change to the id of your current table.
See an example:
$(document).ready( function () {
$('#table_id').DataTable({
"columns": [
{ data: "Nomes", autoWidth: true, visible: false}, null, null
]
});
$(".btn").click(function(){
var linha = $(this).closest("tr");
var texto = $('#table_id').DataTable().row(linha).data().Nomes;
console.log(texto);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdn.datatables.net/1.10.20/css/jquery.dataTables.min.css">
<script src="https://cdn.datatables.net/1.10.20/js/jquery.dataTables.min.js"></script>
<table id="table_id" class="display">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
<th>Column 3</th>
</tr>
</thead>
<tbody>
<tr>
<td>Row 1 Data 1 invisível</td>
<td>Row 1 Data 2</td>
<td><button class="btn">clique</button></td>
</tr>
<tr>
<td>Row 2 Data 1 invisível</td>
<td>Row 2 Data 2</td>
<td><button class="btn">clique</button></td>
</tr>
</tbody>
</table>