- Table Filtering in HTML and JavaScript
- Requirements & Research
- Using TableFilter
- Closing Thoughts
- Как сделать — Фильтра/поиска таблицы
- Фильтр таблицы
- Создание отфильтрованную таблицу
- Пример
- Пример
- Пример
- How TO — Filter/Search Table
- Create A Filtered Table
- Example
- Example
- Example
- JavaScript Table Filter or Search | Add Filter In HTML CSS Table
- Preview Of Add Filter In HTML CSS Tables
- JavaScript Table Filter or Search Source Code
Table Filtering in HTML and JavaScript
GitHub pages makes it easy to share information: just send the URL instead of emailing a file attachment. When I wanted to share the contents of an Excel file this was a natural platform, but with over 1,000 rows of data I needed a way to filter the table on the webpage.
With my knowledge at the time limited to some basic HTML and very little JavaScript, this is an exercise in hacking together a solution. Keep reading to see how I implemented a solution using the TableFilter JavaScript library.
Requirements & Research
With our data to share in a local spreadsheet, the basic requirement is the ability to filter a table on a website on multiple columns just as you can in a spreadsheet:
Being comfortable in Python my first instinct is to filter a Pandas DataFrame. But we are hosting this on GitHub pages as a static website and unable to run the filtering server-side. Therefore, we’ll use JavaScript to filter the table client-side in the browser.
I was able to find a number of examples that provide basic filtering capability with JavaScript, but these are limited to filtering on one column. Eventually I came across the TableFilter JavaScript library, which has great documentation and plenty of examples.
Using TableFilter
To get started, I cloned TableFilter into my repository:
git clone https://github.com/koalyptus/TableFilter.git
We will edit index.html , the HTML file that holds our table and uses tablefilter.js to perform the filtering.
├── assets ├── index.html └── tablefilter └── tablefilter.js
The strategy I used to get a working product is simple and applicable to more general technical challenges:
- Start with a working example that does approximately what you need or more
- Remove or modify features to better align with your use case
- Repeat step 2 until you have what you want
The key here is maintaining a working example throughout and taking a step back if you break something. Iterating a few times on the index.html I borrowed from one of the basic examples, I was left with this:
html lang="en"> head> meta charset="UTF-8"> title>Table Filter Exampletitle> link rel="stylesheet" href="assets/css/bootstrap.min.css"> body> section id="header"> header> h2>Filter Table Exampleh2> header> table id="demo" border="1" class="dataframe"> thead> tr style="text-align: right;"> th>Firstth> th>Lastth> th>Birthdayth> th>Ageth> th>Colorth> th>Heightth> th>Weightth> th>IQth> tr> thead> tbody> tr> td>ZOEtd> td>DAVIStd> td>2012-03-12td> td>6td> td>Yellowtd> td>67td> td>108td> td>81td> tr> . tbody> table> section> body> head> script src="tablefilter/tablefilter.js">script> script data-config=""> var filtersConfig = base_path: 'tablefilter/', auto_filter: delay: 110 //milliseconds >, filters_row_index: 1, state: true, alternate_rows: true, rows_counter: true, btn_reset: true, status_bar: true, msg_filter: 'Filtering. ' >; var tf = new TableFilter('demo', filtersConfig); tf.init(); script>
You can view the original code or a live example of the final product.
Customize this by including the HTML defining the table between and (easy to automate with Python if you need to update the data often). Just below the table definition, we call the tablefilter.js script and define the configuration items.
This leaves us with an easy to filter table:
Closing Thoughts
Is this the best way to share data? Certainly not. But it was a quick solution to a problem I had in a situation (work) where speed and ease are valued at a premium. Furthermore this solution utilizes existing GitHub pages infrastructure and a great open source library.
I hope this example either provides you with a quick solution to a problem I previously had or demonstrates how you may be able to hack together a solution by iterating on a similar working example you can find online.
- All names in this dataset are fake. Any resemblance to real persons, living or dead, is purely coincidental. I made up some data since the data motivating this example is proprietary.
- You can view the original code or a live example of the final product.
- While writing this up I discovered Brython, an implementation of Python 3 in the browser. This is worth checking out in the future.
Как сделать — Фильтра/поиска таблицы
Узнать, как создать фильтр таблицы с помощью JavaScript.
Фильтр таблицы
Как использовать JavaScript для поиска определенных данных в таблице.
Имя | Страна |
---|---|
Alfreds Futterkiste | Германия |
Berglunds snabbkop | Швеция |
Island Trading | Великобритания |
Koniglich Essen | Германия |
Laughing Bacchus Winecellars | Канада |
Magazzini Alimentari Riuniti | Италия |
North/South | Великобритания |
Paris specialites | Франция |
Создание отфильтрованную таблицу
Шаг 1) Добавить HTML:
Пример
Имя | Страна |
---|---|
Alfreds Futterkiste | Германия |
Berglunds snabbkop | Швеция |
Island Trading | Великобритания |
Koniglich Essen | Германия |
Шаг 2) Добавить CSS:
Стиль входного элемента и таблицы:
Пример
#myInput <
background-image: url(‘/css/searchicon.png’); /* Добавить значок поиска для ввода */
background-position: 10px 12px; /* Расположите значок поиска */
background-repeat: no-repeat; /* Не повторяйте изображение значка */
width: 100%; /* Полная ширина */
font-size: 16px; /* Увеличить размер шрифта */
padding: 12px 20px 12px 40px; /* Добавить немного отступов */
border: 1px solid #ddd; /* Добавить серую границу */
margin-bottom: 12px; /* Добавить некоторое пространство под входом */
>
#myTable border-collapse: collapse; /* Свернуть границы */
width: 100%; /* Полная ширина */
border: 1px solid #ddd; /* Добавить серую границу */
font-size: 18px; /* Увеличить размер шрифта */
>
#myTable th, #myTable td text-align: left; /* Выравнивание текста по левому краю */
padding: 12px; /* Добавить отступ */
>
#myTable tr /* Добавить нижнюю границу для всех строк таблицы */
border-bottom: 1px solid #ddd;
>
#myTable tr.header, #myTable tr:hover /* Добавить серый цвет фона для заголовка таблицы и при наведении курсора мыши */
background-color: #f1f1f1;
>
Шаг 3) Добавить JavaScript:
Пример
// Перебирайте все строки таблицы и скрывайте тех, кто не соответствует поисковому запросу
for (i = 0; i < tr.length; i++) td = tr[i].getElementsByTagName("td")[0];
if (td) txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) tr[i].style.display = «»;
> else tr[i].style.display = «none»;
>
>
>
>
Совет: Удалить toUpperCase() если вы хотите выполнить поиск с учетом регистра.
Совет: Изменить tr[i].getElementsByTagName(‘td’)[0] к [1] если вы хотите найти «Страна» (индекс 1) вместо «имя» (индекс 0).
Совет:Кроме того, проверить Фильтр списка.
How TO — Filter/Search Table
How to use JavaScript to search for specific data in a table.
Name | Country |
---|---|
Alfreds Futterkiste | Germany |
Berglunds snabbkop | Sweden |
Island Trading | UK |
Koniglich Essen | Germany |
Laughing Bacchus Winecellars | Canada |
Magazzini Alimentari Riuniti | Italy |
North/South | UK |
Paris specialites | France |
Create A Filtered Table
Step 1) Add HTML:
Example
Name | Country |
---|---|
Alfreds Futterkiste | Germany |
Berglunds snabbkop | Sweden |
Island Trading | UK |
Koniglich Essen | Germany |
Step 2) Add CSS:
Style the input element and the table:
Example
#myInput <
background-image: url(‘/css/searchicon.png’); /* Add a search icon to input */
background-position: 10px 12px; /* Position the search icon */
background-repeat: no-repeat; /* Do not repeat the icon image */
width: 100%; /* Full-width */
font-size: 16px; /* Increase font-size */
padding: 12px 20px 12px 40px; /* Add some padding */
border: 1px solid #ddd; /* Add a grey border */
margin-bottom: 12px; /* Add some space below the input */
>
#myTable border-collapse: collapse; /* Collapse borders */
width: 100%; /* Full-width */
border: 1px solid #ddd; /* Add a grey border */
font-size: 18px; /* Increase font-size */
>
#myTable th, #myTable td text-align: left; /* Left-align text */
padding: 12px; /* Add padding */
>
#myTable tr /* Add a bottom border to all table rows */
border-bottom: 1px solid #ddd;
>
#myTable tr.header, #myTable tr:hover /* Add a grey background color to the table header and on hover */
background-color: #f1f1f1;
>
Step 3) Add JavaScript:
Example
// Loop through all table rows, and hide those who don’t match the search query
for (i = 0; i < tr.length; i++) td = tr[i].getElementsByTagName("td")[0];
if (td) txtValue = td.textContent || td.innerText;
if (txtValue.toUpperCase().indexOf(filter) > -1) tr[i].style.display = «»;
> else tr[i].style.display = «none»;
>
>
>
>
Tip: Remove toUpperCase() if you want to perform a case-sensitive search.
Tip: Change tr[i].getElementsByTagName(‘td’)[0] to [1] if you want to search for «Country» (index 1) instead of «Name» (index 0).
Tip: Also check out Filter List.
JavaScript Table Filter or Search | Add Filter In HTML CSS Table
Previously I have shared a responsive table design, But how we can add a filter option in the table. Maybe you have seen on some websites, where you can search for a specific condition in the table. Like if ever you have visited any websites backend dashboard, then you probably know that we can be filtering out for any user by putting some conditions.
Today you will learn to create filter option for the HTML table using JavaScript . Using this program you can search for specific tables content by searching name, email, id, etc. This is a short & pure JavaScript program for table filter, you can use this on any kind of table on any place. You can use this on your next project, I know using jQuery we can create advanced filtering functions. But it is for showing how can we create the feature using pure JS.
So, Today I am sharing JavaScript Table Filter or Search for HTML Tables. Basically, This program is for Add FIlter In HTML & CSS Based Table. I have used Bootstrap for creating the table’s layout, & used CSS little bit for styling. In this table I have added some data, you add more according to your need. Or another option is to use the JS code & put it your own table.
If you are thinking now how this Filter Table actually is, Then see the preview given below.
Preview Of Add Filter In HTML CSS Tables
See this video preview to getting an idea of how this filter program looks like.
Now you can see this visually. If you like this, then get the source code of its.
JavaScript Table Filter or Search Source Code
In the JavaScript section, I create a variable named var TableFilter and put all the functions inside it. In HTML we stored custom data using Data-* element, Now JS fetches it using . getAttribute method. Now javascript find the filtering text using a function called function _filter ( row ) If any data matches the input then its display that.
I know to explain the JS code in writing is taught, You will automatically understand after getting the codes. If you have some knowledge of JavaScript then you will definitely understand.
For creating this program you have to create 3 files. First for HTML, second for CSS , & third for JavaScript. Follow the steps to creating this without any error.
Create an HTML file named ‘index.html‘ and put these codes given here below.