How to use Bootstrap 4 filters
Overview
Do you want to search from a list or a group of products to make your life a little easier? We can perform this action by using Bootstrap 4 filters.
Bootstrap 4 does not have any specific element with the name of filters that can perform this function. However, the addition of jQuery allows us to conduct this filtration.
We can conduct filtration on tables, lists, or anything using the Bootstrap 4 filters.
Example
First, create a table, a list, or anything like a product’s grid to perform the practical implementation of the filters. Here, we'll create a sample table and implement jQuery on it.
Explanation
- Lines 1 to 11: We start with the
HTMLtag to add all the required bootstrap and JavaScript libraries in theheadtag. We also start thebodytag. - Line 12: We open the
divwhich holds the search bar and product table in it. - Line 13: We add
h2to give a title. This can be optional, according to our needs. - Line 14: We add a search bar using the input tag with an id
myFilter. Inside the tag class, we use theform-controlto make the search bar responsive and expand it to the entire page size. - Line 15: We start the table tag to make it a bordered table using the
bordered-tableclass. - Lines 16 to 22: We define the header of the table. We open the
headtag, then therowtag following thecolumntag. These are the demo names that we can add according to our needs. - Line 23: We open the table
bodytag. Inside the tag, we define its ID asproductTable. This ID is used to define the point where we search the data. - Line 24 to 46: We add dummy values to the product table and close the
divtag.
Code for filtering data from the table
Let's add code to search anything from the table shown above:
Explanation of JavaScript code
- Line 1: We use the
document.readyfunction to confirm the execution of the JavaScript code written inside this function. - Line 2: We define the element and add the value to the search. We also mention when to start the search. The
keyupfunction specifies when the user releases the key. - Line 3: We create a
variablevalue that holds the new value after converting the typed value of the user to lowercase. Here, conversion of lowercase is done to perform a case-insensitive search. - Line 4: We define the part of the table from which the filtration is performed line by line. We then trigger the
filterfunction.
Note: The table body is defined as the starting point of the search to avoid the header part being included in it.
- Line 5: We use
toggleto hide the rows that are not entertained through the search query andtoLowerCaseto make the search case insensitive. The index of-1means the records have no matching values. In the end, we close all the tags.