I have a data table with input fields. When a user enters into a field, I need to find the line number they entered. I asked a question before and got a good answer, but if the data table is responsive and the fields are in a popup, the answer no longer works.
This is my code:
function drawInput(data, type, row, meta) { return '<input id="r' + meta.row + 'c' + meta.col + '" val="' + data + '"></input>'; } var data = [{ c1: 'r1c1', c2: 'r1c2', c3: 'r1c3' }, { c1: 'r2c1', c2: 'r2c2', c3: 'r2c3' }]; $(function() { var table = $('table').dataTable({ info: false, searching: false, ordering: false, paging: false, columns: [{ defaultContent: '<span></span>' }, { data: 'c1', name: 'c1', defaultContent: '<input></input>', render: drawInput }, { data: 'c2', name: 'c2', defaultContent: '<input></input>', render: drawInput }, { data: 'c3', name: 'c3', defaultContent: '<input></input>', render: drawInput } ] }); table.api().rows.add(data); table.api().draw(); $('body').on('change', 'table :input', function(e) { // 找到包含输入字段的行 //console.log(this); var row = table.api().row($(this).closest('td')); // 显示行索引 - 结果为undefined!为什么? console.log(row.index()); }); });
<link href="https://cdn.datatables.net/1.13.6/css/jquery.dataTables.min.css" rel="stylesheet" type="text/css" /> <link href="https://cdn.datatables.net/responsive/2.5.0/css/responsive.dataTables.min.css" rel="stylesheet" type="text/css" /> <script src="https://code.jquery.com/jquery-3.7.0.min.js"></script> <script src="https://cdn.datatables.net/1.13.6/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/responsive/2.5.0/js/dataTables.responsive.min.js"></script> <div style='width:150px;'> <table width="100%" class="responsive"> <thead> <tr> <th></th> <th>Col 1</th> <th>Col 2</th> <th>Col 3</th> </tr> </thead> <tbody> </table> </div>
If you run this code in a large enough window, it will work fine. But if you shrink the window so that the right column drops responsively into sub-rows, the code to find the row index no longer works.
How to correctly find the row of a child cell?
When
.row($(this).closest("td")).index()
is not defined, usetable.api().row(this).index( )
.Strangely,
table.api().row(this)
only works on expanded rows, not original rows, so you need to continue using .closest("td") to get the original row .Specifically,
table.api().row(...)
will return a jQuery object, so to check if any rows were returned, check.length === 0
.gives:
Then
.index()
will give the expected row index.Updated code snippet: