Поиск по таблице html css

Как сделать поиск в таблице на сайте

Всем привет!
В этой статье я выложу готовый скрипт поиска в таблице, используя JQuery.
Например, в таблице могут быть имена одноклассников, либо наименования деталей для авто и т.д.
При наборе в поиске, без перезагрузки сразу будет фильтроваться список по сходству.
Код полностью готов к использованию, вот только нужно будет заменить названия в таблице на свои.

 .results tr[visible='false'], .no-result < display: none; >.results tr[visible='true'] < display: table-row; >.searchCount  Год рождения Место рождения     1 Джеймс Хэтфилд 1963 Калифорния, США  2 Клиффорд Ли Бёртон 1962 Кастро-Валли  3 Ларс Ульрих 1963 Гентофте, Дания  4 Кирк Хеммет 1962 Сан-Франциско, Калифорния  5 Роберт Трухильо 1964 Санта-Моника, Калифорния, США  6 Джейсон Ньюстед 1963 Бэттл Крик, Мичиган      

В таблицу можно добавить сколько угодно списков. Вставьте в таблицу сразу перед

вот такой код (т.д. добавляем остальных):

Номер Имя Год Место рождения  

Если нужно поменять в результате текст «найдено … человек»:

Как сделать поиск в таблице на сайте

Откройте строку №110 и замените русские слова:

$('.searchCount').text('найдено ' + searchCount + ' человек');

searchCount — выводит количество найденных в таблице.

Источник

Как сделать — Фильтра/поиска таблицы

Узнать, как создать фильтр таблицы с помощью 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).

Совет:Кроме того, проверить Фильтр списка.

Источник

JavaScript Table Filter or Search | Add Filter In HTML CSS Table

html css javascript table filter

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.

Источник

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.

Источник

Читайте также:  What is escape character in python
Оцените статью