Простой живой поиск

Как добавить на сайт функционал живого поиска

Живой поиск — это функционал, который позволяет пользователям получать результаты поиска в реальном времени, по мере ввода текста в поле поиска. Это улучшает пользовательский опыт и может помочь увеличить время пребывания на вашем сайте. В этой статье мы рассмотрим, как добавить на сайт функционал живого поиска с использованием JavaScript и AJAX.

Шаг 1: Создание HTML-структуры

Для начала нам нужно создать HTML-структуру страницы. Вам потребуется поле для ввода текста и контейнер для отображения результатов поиска:

Шаг 2: Написание JavaScript-кода

Теперь нам нужно написать JavaScript-код, который будет выполнять поиск и отображать результаты. Мы будем использовать fetch для отправки AJAX-запроса на сервер и получения результатов поиска:

const searchInput = document.getElementById('searchInput'); const searchResults = document.getElementById('searchResults'); searchInput.addEventListener('input', (e) => < const searchText = e.target.value; if (searchText.trim() === '') < searchResults.innerHTML = ''; return; >fetch(`/search?q=$`) .then((response) => response.json()) .then((results) => < searchResults.innerHTML = results.map((result) => ` <div> <h3>$</h3> <p>$</p> </div> `).join(''); >); >);

📘 В этом примере мы используем fetch для отправки запроса на сервер. Вам нужно будет настроить сервер таким образом, чтобы он обрабатывал эти запросы и возвращал результаты в формате JSON.

Читайте также:  Java localdate to timestamp

Шаг 3: Стилизация результатов поиска

Последний шаг — добавить немного стилей для улучшения внешнего вида результатов поиска. Для этого добавьте следующий CSS-код в раздел вашего HTML-файла:

 #searchInput < width: 100%; padding: 8px; font-size: 16px; >#searchResults < margin-top: 16px; >#searchResults div < padding: 8px; border-bottom: 1px solid #ccc; >#searchResults h3 

Теперь у вас есть функциональный живой поиск на вашем сайте! 🎉 Это основы того, как реализовать живой поиск, однако вы можете улучшить его, добавив дополнительные функции, такие как подсветка совпадений, пагинацию и т. д.

Не забывайте тестировать и адаптировать код под ваш проект и серверную часть. Удачной разработки!

Источник

Быстрый поиск с выводом результатов

Виджет на JQuery и AJAX, который покажет результаты поиска непосредственно при вводе в текстовое поле.

Форма

В обычную форму поиска добавляется пустой .

JQuery скрипт получает введенный в поле текст и отправляет его POST-запросом на обработчик /ajax_search.php , ответ выводится в всплывающей плашке.

$(document).ready(function() < var $result = $('#search_box-result'); $('#search').on('keyup', function()< var search = $(this).val(); if ((search != '') && (search.length >1))< $.ajax(< type: "POST", url: "/ajax_search.php", data: , success: function(msg) < $result.html(msg); if(msg != '')< $result.fadeIn(); >else < $result.fadeOut(100); >> >); > else < $result.html(''); $result.fadeOut(100); >>); $(document).on('click', function(e) < if (!$(e.target).closest('.search_box').length)< $result.html(''); $result.fadeOut(100); >>); $(document).on('click', '.search_result-name a', function()< $('#search').val($(this).text()); $result.fadeOut(100); return false; >); $(document).on('click', function(e) < if (!$(e.target).closest('.search_box').length)< $result.html(''); $result.fadeOut(100); >>); >);

Стили формы поиска и результатов:

.search_box < position: relative; >.search_box input[type="text"] < display: block; width: 100%; height: 35px; line-height: 35px; padding: 0; margin: 0; border: 1px solid #fd4836; outline: none; overflow: hidden; border-radius: 4px; background-color: rgb(255, 255, 255); text-indent: 15px; font-size: 14px; color: #222; >.search_box input[type="submit"] < display: inline-block; width: 17px; height: 17px; padding: 0; margin: 0; border: 0; outline: 0; overflow: hidden; text-indent: -999px; background: url(https://snipp.ru/demo/127/search.png) 0 0 no-repeat; position: absolute; top: 9px; right: 16px; >/* Стили для плашки с результатами */ .search_result

Источник

Пишем свой простой вариант «живого поиска».

Сегодня я напишу статью, о том как сделать простую версию так называемого «живого поиска». Для тех кто не в курсе, живой поиск — это когда при вводе искомого текста, появляется подсказка, с возможными вариантами. Примером тому служит Яндекс и Google.

По сути «живой поиск» это обычный AJAX скрипт, который обращается к базе данных, производит в ней поиск, и возвращает ответ скрипту. Для работы поиска я буду использовать Jquery.

Итак, создадим простую форму поиска:

     .search_area < width: 350px; margin: 0px; position: relative; >#search_box < width:200px; padding:2px; margin:1px; border:1px solid #000; >#search_advice_wrapper < display:none; width: 350px; background-color: rgb(80, 80, 114); color: rgb(255, 227, 189); -moz-opacity: 0.95; opacity: 0.95; -ms-filter:"progid:DXImageTransform.Microsoft.Alpha"(Opacity=95); filter: progid:DXImageTransform.Microsoft.Alpha(opacity=95); filter:alpha(opacity=95); z-index:999; position: absolute; top: 24px; left: 0px; >#search_advice_wrapper .advice_variant < cursor: pointer; padding: 5px; text-align: left; >#search_advice_wrapper .advice_variant:hover < color:#FEFFBD; background-color:#818187; >#search_advice_wrapper .active   Обратите внимание на autocomplete="off" у input'а, это для того чтобы отключить подсказки браузера, которые он показывает при повторном наборе текста в форме.

Теперь займемся созданием javascript скрипта.

  

Я постарался описать этот скрипт по максимуму в комментариях. По сути скрипт делется на несколько частей:

  1. Считываем ввод с клавиатуры, получаем данные из базы данных и выводим их
  2. Делаем скрытие слоя с подсказками, при нажатии на Escape и Enter
  3. Делаем переход по слою с подсказками, через нажатие стрелок клавиатуры ( вверх и вниз)
  4. Скрытие слоя с подсказками при клике на поле сайта и открытие его при клике на input
  5. При клике на подсказку мы вписываем слово в input поиска и прячем форму подсказки.

А теперь давайте посмотрим содержимое файла /ajax/ajax.php, к которому мы подключаемся за теми самыми подсказками.

if(!empty($_GET['query']))< $query = (string)$_GET['query']; $array = array(); $request = $db->query("SELECT `description`, `name` FROM `prefix_name` WHERE `description` LIKE '%". $db->real_escape_string($query) . "%' OR `name` LIKE '%". $db->real_escape_string($query) . "%' LIMIT 0, 10"); while($data =$db->fetch_assoc($request)) < $array[] = $data['name']; >echo "['".implode("','", $array)."']"; > exit();

Источник

Adding live search functionality to a Vanilla JavaScript project. 2020 Tutorial with code examples.

Today we will work on a more real-world scenario, implementing a live search in JavaScript!

In our example, we will use an array of names and countries. We will then have a search bar. On input, it filters the array to showcase only matching search results.

Try and search for something (e.g., Japan or Abel)

h1>JavaScript live searchh1> input autocomplete="off" type="search" id="search" placeholder="Search for a country or name!" /> ul id="results">ul>

In today’s article, we are more focused on the JavaScript part than actual the HTML structure or styling, so a basic setup.

As for the CSS, we added some basic styling to make it all centered with Flex and look a little bit nicer.

body  display: flex; min-height: 100vh; align-items: center; font-family: Roboto, 'Helvetica Neue', Arial, sans-serif; flex-direction: column; > input  width: 250px; text-align: center; > ul  list-style: none; display: flex; flex-direction: column; align-items: center; padding: 0; >

Step 3: JS code for the live search function permalink

Now on to the magic part. In this example, I prepared a random array of data consisting of the following structure:

const data = [ < name: 'Ryan', country: 'Saint Lucia' >, // 99 more ];

Then we need to define the variables we are going to use.

const search = document.getElementById('search'); const results = document.getElementById('results'); let search_term = '';

The search variable is our input element, results are our ul list, and the search_term is whatever we input in our search field.

Now let’s create a JavaScript function to capture the search input.

search.addEventListener('input', (event) =>  search_term = event.target.value.toLowerCase(); showList(); >);

Here we add an input listener to our search and capture the value (in lowercase), then we call a function called showList which we will build now.

In there, we start with clearing whatever is on the list already.

const showList = () =>  results.innerHTML = ''; >;

Now we want to loop over all our data elements:

We make use of the filter ES6 function.

In there, we want to check if the country’s name matches our search string.

data.filter((item) =>  return ( item.country.toLowerCase().includes(search_term) || item.name.toLowerCase().includes(search_term) ); >);

As you can see, we match either on country OR (||) on the name. Now in the filter, we get a single item from our array. We then check if the value in lowercase matches (includes) our search term.

If so, we return this. Remember that filter will then modify on its own.

The last step is to append a new list item to our ul .

data .filter((item) =>  return ( item.country.toLowerCase().includes(search_term) || item.name.toLowerCase().includes(search_term) ); >) .forEach((e) =>  const li = document.createElement('li'); li.innerHTML = `Name: $e.name> || Country: $e.country>`; results.appendChild(li); >);

There you go! All that’s left is to call the method initially.

Place the following at the bottom of your scripts.

Thank you for reading this tutorial, and let’s connect! permalink

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Источник

Оцените статью