Taking value from a hidden column of datatables?

Asked

Viewed 464 times

3

How do I get the value of a column with the visible: false?

 "columns": [
                    { data: "Nomes", autoWidth: true, visible: false},   
            ]

Example of the Names column, I’m currently doing so.

$(this).parent().parent().find('td').eq(0).text()

Only if I do it this way he won’t return if the column is with visible: false

1 answer

2


When Datatables is rendered, invisible columns are completely deleted from the DOM, therefore being inaccessible via common Javascript. You need to use the component API, that is, the method Row(). date() will return the line data via JSON.

To catch the line of the clicked element you use:

var linha = $(this).closest("tr");

The .closest("tr") will fetch the first element tr parent of the clicked element.

How the column is named with the term Nomes, just take the value of .data().Nomes of Row returned in variable linha:

var texto = $('#table_id').DataTable().row(linha).data().Nomes;

The selector '#table_id' is the table id. Change to your table id current table.

Take 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 rel="stylesheet" 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>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.