Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

datatables - Read Value of Hidden Column in JQuery

I need to hide a column on the table, but after that I cannot read selected row's hidden column value.

 dtTable = $('#lookupTable').DataTable({
       "columnDefs": [
           {
               "targets": [ 0 ],
               "visible": false,
               "searchable": false               
           }
        ],  

        aaData: data,
        aoColumns: cols,
        paging: false,
        scrollCollapse: true,
        destroy: true

    });

as you see the first column is hidden now. And I am trying to read the column value with that code

    selectedIndex = $(this).find('td:eq(0)').text(); 

if i delete <"visible": false> from the code i can read the first column's value, but if it is hidden it gives me second column value.

I tired to change "witdh" property but it didnt work..

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The CSS selector wont work, because "visible": false in your columnDefs does not mean that the column gets the equivalent display: none; style property in the markup.

Instead, you'll have to use the DataTables API to get the data in the hidden column.

The function fnGetData will do the trick. It returns the text data in the cell that is passed as an argument to the function.

Heres the example from the documentation

oTable.$('td').click( function () {
    var sData = oTable.fnGetData( this );
    alert( 'The cell clicked on had the value of '+sData );
});

In your case, the column is hidden, thus you'll have to combine it with a second API call. Say that you click the row with the hidden first column, you can combine the fnGetData with the fnGetPosition function.

var position = dtTable.fnGetPosition(this);
var hiddenColumnValue = dtTable.fnGetData(position)[0];

Check the documentation, it has some great examples.

fnGetData()

fnGetPosition()

This is the working code

  $('#lookupTable tbody').on('click', 'tr', function () {

        selectedIndex = dtTable.row(this).data()[0];   
 });

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...