Datatable column select filter sort() not working when column have link

I am using datatable column select filter. In one of the column I have html link tag, this cause to show unsorted select options at the top

<th><a href="{{route('customer.information', $customer->id)}}">{{ $customer->name }}</a></th>
<script>
      $(document).ready(function() {
      $('#colSearch').DataTable( {
         "order": [],

         initComplete: function () {
            this.api().columns([0,1,2,3,4,5,6]).every( function () {
               var column = this;
               var colTitle = this.header().innerHTML;
               var select = $('<select><option value="">Select ' + colTitle + '</option></select>')
                  .appendTo( $(column.footer()).empty() )
                  .on( 'change', function () {
                     var val = $.fn.dataTable.util.escapeRegex(
                        $(this).val()
                     );

                     column
                        .search( val ? '^'+val+'$' : '', true, false )
                        .draw();
                  } );

               column.data().unique().sort().each( function ( d, j ) {
                  var val = $('<div/>').html(d).text();
                  select.append( '<option value="' + val + '">' + val + '</option>' );
               } );
            } );
         }
      } );
   } );
   </script>

You can check the example datatable http://live.datatables.net/cikaqoxe/1/

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

This is happening because:

(1) column.data() extracts the entire contents of each column cell – including any HTML which may also exist in the cell.

(2) you are then sorting that extracted data. Therefore, instead of sorting using Tiger Nixon, you are actually using <a href="">Tiger Nixon</a>.

To fix this you can wait until you have removed the HTML before you sort your data. For example:

var opts = [];
column.data().unique().each( function ( d, j ) {
  opts.push( $('<div/>').html(d).text() );          
} );
opts.sort();
opts.forEach(function (item, index) {
  select.append( '<option value="' + item + '">' + item + '</option>' );
} );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x