0

I am using the DataTables plugin for a bootstrap 4 table with dynamic info (https://datatables.net/). I'm getting information from different API's, building an object and appending to the table.

Everything works fine, but i want to be able to create some filter buttons on things that are NOT displayed to the user in the table.

I've got a few columns which i can use to order/search (default datatables), but i want to be able to filter from data-region and data-subregion HTML attributes. I've read about data-search from DataTables plugin, but since i need more than 1 filter (as i said, from -region & -subregion would be a start, but will probably expand) that is not really useful to me.

My idea is to create a dropdown menu (for look n feel purposes) and link the buttons to the filter. The filter will check what button was pressed (button text) and filter the entire table based on it (like a search, but for data html attributes).

I've tried searching all day for something similar and found nothing....Hopefully someone here used DataTables like this and can give me a hint on how to do it.

Thanks in advance.

7
  • It appears that the current DateTables API only has 2 filter options; neither of which perform the search as you want. You can inject HTML into the generated DataTables HTML which can then perform your filters, or you can modify the behavior of the search box attaching your own events to the search box once it has been generated and is made available to the DOM. I have used this method to add dropdown filters of my own choosing to the resulting DataTables. Commented Jul 3, 2018 at 20:06
  • By inject HTML you mean add new table cols with the needed info for each item or something else? The data-region, data-subregion etc are already inside the html (to be more exact they are data attributes inside each item's title). The modify behaviour part is what i need, but i have no idea on where to start. I've checked their documentation, past stack questions, but i really dont understand how to do it. Can you by any chance share a bit of code on how you did the dropdown filtering ? Thanks. Commented Jul 4, 2018 at 7:35
  • The DataTables api adds elements to the table for searching and paging and whatever other options you implement that they have. What I mean is that once that api generates it's HTML, you can then use JavaScript to identify those elements and containers and inject your own HTML into that with custom functionality. Commented Jul 5, 2018 at 12:27
  • for example: on the landing page of the DataTables website (your link in question) they have an example. Inspect the elements and you can find class names like "dataTables_wrapper" and "dataTables-filter." Using JavaScript, document.querySelector('.dataTables_wrapper'), you can add the HTML wherever you like. Commented Jul 5, 2018 at 12:29
  • I already said that the information IS in the html, ex (not a real one) <span class="blabla" data-region="Region" data-subregion="subregion"></span> Commented Jul 5, 2018 at 18:25

3 Answers 3

1

Well I haven't found any way to do it so I gave up. I created some new columns with the information that I previously stored in 'data' attribute. I hid the columns and used the table reference for the api

table.columns(colnumber).search('text').draw()

Not pretty, but it works so I'm not going to waste more time on finding a different approach.

Sign up to request clarification or add additional context in comments.

Comments

0

There's probably a more elegant way to do this as a JQuery & DataTables plug-in, but this is simple and works.

Here is the HTML for a table:

<table style="width:100%;border-collapse:collapse;border:solid 1px black;">
        <thead>
            <tr>
                <th>Column 1</th>
                <th>Column 2</th>
            </tr>
        </thead>
        <tbody>
            <tr data-region="1" data-subregion="a">
                <td>Region 1</td>
                <td>Sub-Region A</td>
            </tr>
            <tr data-region="1" data-subregion="b">
                <td>Region 1</td>
                <td>Sub-Region B</td>
            </tr>
            <tr data-region="2" data-subregion="a">
                <td>Region 2</td>
                <td>Sub-Region A</td>
            </tr>
            <tr data-region="2" data-subregion="b">
                <td>Region 2</td>
                <td>Sub-Region B</td>
            </tr>
            <tr data-region="2" data-subregion="c">
                <td>Region 2</td>
                <td>Sub-Region C</td>
            </tr>
            <tr data-region="3" data-subregion="a">
                <td>Region 3</td>
                <td>Sub-Region A</td>
            </tr>
        </tbody>
    </table>

Configure the DataTables and add your custom elements for filtering.

$(document).ready(function(){

        // Execute the DataTables API on the table(s)
        $('table').DataTable();

        // give the DataTables API a moment to finish drawing elements to the DOM
        setTimeout(function(){
            // Just adding some Dropdown lists, but you can add a custom search box
            // this first one filters by the data-region attribute
            var regionFilter = $('<select data-filter="region">'
                + '<option value="0">All Regions</option>'
                + '<option value="1">Region 1</option>'
                + '<option value="2">Region 2</option>' 
                + '<option value="3">Region 3</option>' 
                + '</select>');
            // this second one filters by the data-subregion attribute
            var subregionFilter = $('<select data-filter="subregion">'
                + '<option value="0">All Sub-Regions</option>'
                + '<option value="a">Sub-Region A</option>'
                + '<option value="b">Sub-Region B</option>' 
                + '<option value="c">Sub-Region C</option>' 
                + '</select>');
            // prepend the dropdown lists into the dataTables_filter container
            // optionally, you can overwrite the default search box that the DataTables API places here
            $('.dataTables_filter').prepend(regionFilter);
            $('.dataTables_filter').prepend(subregionFilter);
            // give your own HTML a moment to draw to the DOM
            setTimeout(function(){
                // configure the selection to trigger the filter action
                $('select[data-filter]').on('change', function(){
                    // the <select> element has a data-filter attribute which defines which attribute to search the table for
                    var dataFilter = $(this).attr('data-filter');
                    var keyword = $('select[data-filter="' + dataFilter + '"] option:selected').val();
                    // execute the search
                    searchDataAttributes(dataFilter, keyword);
                });
            }, 300);
        }, 400);

    });

Create your own search implementation

// This search is very simple - you can implement any type of search you like
    function searchDataAttributes(attribute, keyword) {
        // put together the attribute to search
        var dataAttribute = 'data-' + attribute;
        // the value 0 is being used to show all
        if (keyword=='0') {
            $('tbody tr').show();
            return true;
        }
        // if the keyword is not 0, then look at the attributes of each row in the table
        $('tbody tr').each(function(){
            var attributeValue = $(this).attr(dataAttribute);
            // if the value of the attribute in the row matches the value of the keyword, then show the row
            if (attributeValue==keyword) {
                console.log('show');
                $(this).show();
            } else {
                console.log('hide');
                $(this).hide();
            }
        });
    }

This is a simple dropdown list filter. You can replace the search box with your own custom search box that searches the way you want it to. You don't have to let DataTables draw their search box at all if you don't want to. This is just one way of getting around the limits of the DataTables out of the box.

2 Comments

I appreciate you taking the time to write all that, but its definitely not what i am looking for. I have pagination on the page, also that is not a DataTables search, its a show/hide in jquery. I've tried that before asking, but there are several problems with the approach -> 1 - Hide/Show is going to break pagination (You might have pages that have less than X items because they are hidden and DataTables doesnt seem to check for hidden rows) 2 - Hide/Show doesnt use the DataTables api for search and/or other features so it makes it useless. That approach would be best without using DT.
@DanteR. I explained that this is a simple example of the approach. It is up to you to figure out how to implement the search the way you want it to work. If you don't like this approach or don't understand it, then that's fine.
0

Use Bootstrap Dropdowns in datatables.net

  1. Copy any dropdowns from Bootstrap, https://getbootstrap.com/docs/4.5/components/dropdowns/
  2. Create a javascript function that returns the dropdown html from bootstrap, see below:
function SearchHtml(){
        return '<div class="position-relative">' + 
  '<button class="btn btn-block btn-soft-secondary dropdown-toggle" href="javascript:;" role="button"' + 
       'aria-haspopup="true"' + 
       'aria-expanded="false"' + 
       'data-unfold-event="click' + "
       'data-unfold-target="#filter3Dropdown"' + 
       'data-unfold-type="css-animation"' + 
       'data-unfold-duration="300"' + 
       'data-unfold-delay="300"' + 
       'data-unfold-animation-in="slidefadeIn"' + 
       'data-unfold-animation-out="fadeOut">' + 
        '<span class="fas fa-sliders-h dropdown-item-icon"></span>' + 
        'Refine' + 
  '</button>' + 
  '<div id="filter3Dropdown" class="dropdown-menu dropdown-unfold dropdown-menu-sm-right dropdown-menu-size-lg p-5" aria-labelledby="filter3DropdownInvoker">' + 
      '<div class="row">' + 
          '<div class="col-md-12">' + 
             '<!-- create your html refine search parameters here -->' + 
          '</div>' + 
      '</div>' + 
  '</div>' + 
'</div>';
    }
  1. Just remove all the dropdown items inside the dropdown menu, and then create/construct your html search parameters.

  2. From datatable initialization, set the button text to SearchHtml(). For the className, adjust button classes because button will appear bigger with padding.


    buttons: [
                {
                    text: SearchHtml(),   
                    className: 'btn-sm btn-rounded p-0 border-primary'
                }
            ]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.