Append custom control to dom using dataTables with

2019-04-12 06:43发布

I have added a select(dropdown) for datatables search box for searching per column and trying to add that select to searchbox as below->

var table = $('#example').DataTable({
 dom: '<l<"toolbar">f>rtip',
            language: {
                search: "_INPUT_", //To remove Search Label
                searchPlaceholder: "Search..."
            }
})  
$("div.toolbar").html(select);

CSS

.toolbar {
        float: right;
    }

It actually worked on fiddle -> https://jsfiddle.net/32v2qpj1/5/

Surprisingly length and filter position has been changing when I implemented the same on my .aspx page like below image. Bootstrap row and col grids are missing whenever I use dom. It adding as a 2 seperate rows for length and search and as same at footer. I tried examples from https://datatables.net/reference/option/dom to check if my code is wrong. It's just re-positioning when use DOM!

datatable alignment missing

I have no idea why it is re-positioning when only added dom. I was wondering is there any other way to add select control to the search box?

1条回答
一纸荒年 Trace。
2楼-- · 2019-04-12 07:39

Well. If you set the dom option, then you overwrite the default dom setting which in dataTables with Bootstrap is :

"<'row'<'col-sm-6'l><'col-sm-6'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",

There is no reason for injecting a .toolbar when we have a predefined setup like this. Instead give the filter section a little more space :

"<'row'<'col-sm-5'l><'col-sm-7'f>>" +

and define a maximum width for the #select :

select#select {
  width: 100px;
  display: inline-block;
} 

Finally add standard Bootstrap classes to the #select :

<select id="select" class="form-control input-sm">

and append the select to .dataTables_filter :

$(".dataTables_filter").append(select);

This give the responsive experience we want from Bootstrap.

updated fiddle -> https://jsfiddle.net/32v2qpj1/6/


NB: Remember to remove jquery.dataTables.min.css if you use bootstrap! Instead, style the <table> the Bootstrap way :

<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
查看更多
登录 后发表回答