jQuery Datatable: Heading and Search on the same line

Viewed 639

At the moment my jQuery Datatable looks like this:

Picture

and I would like to have the History heading and the search bar on the same line.

I have implemented the heading and table like this:

<h2>History</h2>
<table class="table" id="history_tbl" style="width:100%">
    <thead>
        <tr>
            ...
        </tr>
    </thead>
    <tbody>
        @for (var i = 1; i < M.Count(); i++)
        {
        <tr>
            ...
        </tr>
        }
    </tbody>
</table>

And the following specifications for the Datatable:

$("#history_tbl").DataTable({
                "columns": [
                    { searchable: false },
                    null,
                    { searchable: false },
                    { searchable: false },
                    { searchable: false },
                    { searchable: false },
                    { searchable: false }
                ],
                ordering: false,
                paging: true,
                lengthChange: false,
                language: {
                    searchPlaceholder: "Search names",
                    search: ""
                }
            });

I've seen that I can change something by adding DOM, but I'm not quite sure what I need in my case.

I appreciate any help!

1 Answers

Here are two options - both of which are less than ideal:

Option One

One approach, using the dom option that you mentioned, is this:

$('#example').DataTable( {
  dom: '<"title"<"filter"f>>rtip'
} );

This places the f filter control in its own div with a style class of filter, and then also wraps that in another div with a style class of title.

Then we need the following style section in the <head> of the HTML page:

.title::before {
  font-size: 2em;
  margin: 1.5em 0 0 0;
  content: "History";
}

.filter {
  float: right;
}

Finally, the <h2>History</h2> element needs to be removed from your page, to use this approach.

My end result is this:

enter image description here

This approach has a couple of important drawbacks:

  1. It forces you to place some content (the heading) in CSS - whereas style and content are supposed to be kept separate.

  2. This could make it harder to implement internationalization (if that is needed).

Option Two

Alternatively, you can use the <h2> tag, with some relative positioning - for example:

<div style="position: relative; top: 30px;"><h2>History</h2></div>

This pushes the title down from the top by 30px (you may need to adjust that to your specific needs).

In this case you do not need to use the <dom> option, or the related styles from the first option.

This also has some important drawbacks:

  1. It can be brittle - having unexpected/unwanted behavior in some situations (e.g. different screen resolutions).

  2. You may have an unwanted gap of white space at the top of the page, which requires additional styling work-arounds to remove.

Related