randommman randommman - 6 months ago 11
jQuery Question

Adding individual column search on seprate row

I want to add text boxes to search my datatables (which i have done) but the position of them is in the same

<Tr>
as my row titles.

As you can see here:

enter image description here

But I want to make the inputs go on the seperate row so they're split like so:

enter image description here

My code:

if (!$.fn.DataTable.isDataTable('.table')) {
$('.table thead th').each( function (i) {
var title = $('.table thead th').eq( $(this).index() ).text();
$(this).after('<input type="text" placeholder="Search '+title+'" data-index="'+i+'" />' );
} );

var table = $('.table').DataTable( {
paging: false
} );


$( table.table().container() ).on( 'keyup', 'thead input', function () {
table
.column( $(this).data('index') )
.search( this.value )
.draw();
} );
}


How can I achieve this?

Answer

You need to create another row.

var ths = $('.table thead th');
var searchTr = $('<tr></tr>');
searchTr.insertAfter(ths.parents('tr'));
searchTr.append(ths.map(function (i) {
  var title = $(this).text();
  return $('<td><input type="text" placeholder="Search '+title+'" data-index="'+i+'" /></td>')[0];
}));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="table">
  <thead>
    <tr>
      <th>Header1</th><th>Header2</th><th>Header3</th><th>Header4</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <th>Content1</th><th>Content2</th><th>Content3</th><th>Content4</th>
    </tr>
  </tbody>
</table>