Как сделать окно поиска в html

Обновлено: 01.05.2024

The value attribute contains a DOMString representing the value contained in the search field. You can retrieve this using the HTMLInputElement.value property in JavaScript.

If no validation constraints are in place for the input (see Validation for more details), the value can be any text string or an empty string ( "" ).

Additional attributes

Attribute Description
list The id of the element that contains the optional pre-defined autocomplete options
maxlength The maximum number of characters the input should accept
minlength The minimum number of characters long the input can be and still be considered valid
pattern A regular expression the input's contents must match in order to be valid
placeholder An exemplar value to display in the input field whenever it is empty
readonly A Boolean attribute indicating whether or not the contents of the input should be read-only
size A number indicating how many characters wide the input field should be
spellcheck Controls whether or not to enable spell checking for the input field, or if the default spell checking configuration should be used

The values of the list attribute is the id of a element located in the same document. The provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

maxlength

The maximum number of characters (as UTF-16 code units) the user can enter into the search field. This must be an integer value 0 or higher. If no maxlength is specified, or an invalid value is specified, the search field has no maximum length. This value must also be greater than or equal to the value of minlength .

The input will fail constraint validation if the length of the text entered into the field is greater than maxlength UTF-16 code units long.

minlength

The minimum number of characters (as UTF-16 code units) the user can enter into the search field. This must be a non-negative integer value smaller than or equal to the value specified by maxlength . If no minlength is specified, or an invalid value is specified, the search input has no minimum length.

The search field will fail constraint validation if the length of the text entered into the field is fewer than minlength UTF-16 code units long.

pattern

See the section Specifying a pattern for details and an example.

placeholder

The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See Placeholders are not accessible in : The Input (Form Input) element for more information.

readonly

A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

The size attribute is a numeric value indicating how many characters wide the input field should be. The value must be a number greater than zero, and the default value is 20. Since character widths vary, this may or may not be exact and should not be relied upon to be so; the resulting input may be narrower or wider than the specified number of characters, depending on the characters and the font ( font settings in use).

This does not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute.

spellcheck

Non-standard attributes

The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can't be helped.

Attribute Description
autocorrect Whether or not to allow autocorrect while editing this input field. Safari only.
incremental Whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.).
mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android only.
results The maximum number of items that should be displayed in the drop-down list of previous search queries. Safari only.

autocorrect Non-Standard

incremental Non-Standard

The Boolean attribute incremental is a WebKit and Blink extension (so supported by Safari, Opera, Chrome, etc.) which, if present, tells the user agent to process the input as a live search. As the user edits the value of the field, the user agent sends search events to the HTMLInputElement object representing the search box. This allows your code to update the search results in real time as the user edits the search.

If incremental is not specified, the search event is only sent when the user explicitly initiates a search (such as by pressing the Enter or Return key while editing the field).

The search event is rate-limited so that it is not sent more more frequently than an implementation-defined interval.

mozactionhint Non-Standard

results Non-Standard

The results attribute—supported only by Safari—is a numeric value that lets you override the maximum number of entries to be displayed in the element's natively-provided drop-down menu of previous search queries.

The value must be a non-negative decimal number. If not provided, or an invalid value is given, the browser's default maximum number of entries is used.

Using search inputs

elements of type search are very similar to those of type text , except that they are specifically intended for handling search terms. They are basically equivalent in behavior, but user agents may choose to style them differently by default (and, of course, sites may use stylesheets to apply custom styles to them).

Basic example

This renders like so:

q is the most common name given to search inputs, although it's not mandatory. When submitted, the data name/value pair sent to the server will be q=searchterm .

You must remember to set a name for your input, otherwise nothing will be submitted.

Differences between search and text types

The main basic differences come in the way browsers handle them. The first thing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome:

In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox:


At this point, let's look at some useful techniques you can apply to your search forms.

Setting placeholders

You can provide a useful placeholder inside your search input that could give a hint on what to do using the placeholder attribute. Look at the following example:

You can see how the placeholder is rendered below:

Search form labels and accessibility

One problem with search forms is their accessibility; a common design practice is not to provide a label for the search field (although there might be a magnifying glass icon or similar), as the purpose of a search form is normally fairly obvious for sighted users due to placement (this example shows a typical pattern).

This could, however, cause confusion for screenreader users, since they will not have any verbal indication of what the search input is. One way around this that won't impact on your visual design is to use WAI-ARIA features:

  • A role attribute of value search on the element will cause screenreaders to announce that the form is a search form.
  • If that isn't enough, you can use an aria-label attribute on the itself. This should be a descriptive text label that will be read out by the screenreader; it's used as a non-visual equivalent to .

Let's have a look at an example:

You can see how this is rendered below:

There is no visual difference from the previous example, but screenreader users have way more information available to them.

Note: See Signposts/Landmarks for more information about such accessibility features.

Physical input element size

The physical size of the input box can be controlled using the size attribute. With it, you can specify the number of characters the input box can display at a time. In this example, for instance, the search box is 30 characters wide:

The result is this wider input box:

Validation

elements of type search have the same validation features available to them as regular text inputs. It is less likely that you'd want to use validation features in general for search boxes. In many cases, users should just be allowed to search for anything, but there are a few cases to consider, such as searches against data of a known format.

Note: HTML form validation is not a substitute for scripts that ensure that the entered data is in the proper format. It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database.

A note on styling

There are useful pseudo-classes available for styling valid/invalid form elements: :valid and :invalid . In this section, we'll use the following CSS, which will place a check (tick) next to inputs containing valid values, and a cross next to inputs containing invalid values.

Making input required

You can use the required attribute as an easy way of making entering a value required before form submission is allowed:

This renders like so:

In addition, if you try to submit the form with no search term entered into it, the browser will show a message. The following example is from Firefox:

form field with attached message that says Please fill out this field

Different messages will be shown when you try to submit the form with different types of invalid data contained inside the inputs; see the below examples.

Input value length

You can specify a minimum length, in characters, for the entered value using the minlength attribute; similarly, use maxlength to set the maximum length of the entered value.

The example below requires that the entered value be 4–8 characters in length.

This renders like so:

If you try to submit the form with less than 4 characters, you'll be given an appropriate error message (which differs between browsers). If you try to go beyond 8 characters in length, the browser won't let you.

Specifying a pattern

You can use the pattern attribute to specify a regular expression that the inputted value must follow to be considered valid (see Validating against a regular expression for a simple crash course).

Let's look at an example. Say we wanted to provide a product ID search form, and the IDs were all codes of two letters followed by four numbers. The following example covers it:

This renders like so:

Examples

You can see a good example of a search form used in context at our website-aria-roles example (see it live).

Specifications

Specification Status Comment
HTML Living Standard
Определение '' в этой спецификации.
Живой стандарт Initial definition
HTML 5.1
Определение '' в этой спецификации.
Рекомендация Initial definition

Browser compatibility

No compatibility data found for html.elements.input.type_search .
Check for problems with this page or contribute missing data to mdn/browser-compat-data.

На сайтах часто востребован поиск по ключевым словам, для ввода которых используется текстовое поле. В HTML5 для поиска добавлено новое поле, синтаксис его следующий:

Используемые атрибуты совпадают с текстовым полем.

Добавление предложений в поисковый плагин

Поисковик Google был один из первых, кто добавил к своему поиску предложение популярных запросов — вы набираете текст и сразу же получаете список слов начинающихся с введенных символов. В дальнейшем эта технология стала настолько популярна, что теперь ее можно встретить повсеместно. Также она включена и в спецификацию OpenSearch, на основе которой работает поисковый плагин для браузера.

Поиск по сайту через Google и Яндекс

Поиск на сайте, где много информации, это один из способов отыскать и прочитать нужный материал. Эта мысль настолько очевидна, что никакого подтверждения не требует, поэтому практически во все системы управления сайтом поиск вставлен по умолчанию. Как быть, если подобный поиск по каким-либо причинам не устраивает или вообще отсутствует? Позаимствовать систему поиска у Google или Яндекса. И у той и другой компании есть прекрасные средства для организации поиска по одному или нескольким ресурсам.

Поисковый плагин для сайта

В интерфейс браузера Firefox, начиная с версии 2.0 встроена строка поиска, позволяющая без захода на сайт вводить поисковые запросы к Гуглу, Яндексу и другим системам. Идея оказалась удачной и ее впоследствии подхватили разработчики других браузеров. Несмотря на то, что подобным поиском пользуются многие, включая и создателей сайтов, большинство из них не подозревают, насколько просто и легко сделать собственный поисковый плагин для сайта. Плюсов у такого плагина несколько: пользователи начинают активнее использовать поиск, возрастает количество посетителей, повышается результативность сайта, улучшается юзабилити. Главное, что затрат практически нет. Если на сайте используется поиск, «прикрутить» для него плагин раз плюнуть.

Поиск на сайте, где много информации, это один из способов отыскать и прочитать нужный материал. Эта мысль настолько очевидна, что никакого подтверждения не требует, поэтому практически во все системы управления сайтом поиск вставлен по умолчанию. Как быть, если подобный поиск по каким-либо причинам не устраивает или вообще отсутствует? Позаимствовать систему поиска у Google или Яндекса. И у той и другой компании есть прекрасные средства для организации поиска по одному или нескольким ресурсам.

Система пользовательского поиска Google

После чего необходимо пройти три простых шага для настройки поиска. На первом шаге (рис. 1) следует указать имя поиска, выбрать язык, ввести один или несколько сайтов для поиска и принять условия предоставления услуг. Из предложенных версий берем бесплатный стандартный пакет. Также можно добавить необязательное описание нашего поиска.

Настройка системы поиска Google

Рис. 1. Настройка системы поиска Google

На втором шаге выбирается стиль оформления строки поиска (рис. 2). Вы можете выбрать готовый вариант из списка, либо изменить существующий вариант, нажав на кнопку «Настроить». В этом случае становится доступна модификация некоторых цветов и шрифта.

Оформление поиска

Рис. 2. Оформление поиска

Настройки поиска можно задать и позже, когда он будет создан, либо вообще отказаться от предложенной формы и сделать свою, с карточными играми и профурсетками.

На последнем шаге выводится код для вставки к себе на сайт (рис. 3).

Код пользовательского поиска

Рис. 3. Код пользовательского поиска

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

Яндекс.Поиск для сайта

На первом шаге (рис. 4) нужно ввести название поиска, указать один или несколько сайтов и согласиться с условиями предоставления сервиса.

Описание поиска

Рис. 4. Описание поиска

На втором шаге настраивается вид и цвета поисковой формы (рис. 5).

Настройка поисковой формы

Рис. 5. Настройка поисковой формы

Если вы включили пункт «показывать подсказки в строке поиска» при вводе текста будет отображаться список популярных запросов, начинающихся с набранных символов.

На третьем шаге задаются цвета и шрифт результатов поиска (рис. 6). Также указывается, где их выводить: на сайте Яндекса или на отдельной странице сайта.

Оформление результатов поиска

Рис. 6. Оформление результатов поиска

Нажатие на кнопку «Далее» и вы получаете готовый код формы для вставки его к себе на сайт (рис. 7). Дополнительно можно указать кодировку страниц сайта и сразу же проверить работу поиска. Если что-то не понравится, есть возможность вернуться к предыдущим шагам и внести соответствующие изменения.

Получение кода формы

Рис. 7. Получение кода формы

Варианты поиска

Поиск через стороннюю систему имеет два основных варианта.

  1. При вводе текста вы перенаправляетесь на сайт поисковой системы с результатами выдачи по текущему сайту. При нажатии по результатам происходит переход на сайт с найденным текстом.
  2. При вводе текста совершается переход на определенную страницу сайта с результатами поиска.

Кроме этого, Google предлагает вариант, когда результаты отображаются поверх текущей страницы в отдельном слое.

Мне больше импонирует второй вариант, поиск при этом интегрируется в сайт и воспринимается как его часть. Код в этом случае разбивается на два блока — один для отображения формы поиска, второй для вывода результатов поиска. Также надо завести отдельную страницу, куда будут перенаправляться пользователи для просмотра результатов.

Особенности поиска

Надо понимать, что поиск с помощью поисковой системы осуществляется не по самому сайту, а по собственному индексу поисковика. Соответственно, только что добавленные статьи не будут отображаться в поиске, пока до них не доберется «паук» и не проиндексирует содержимое статьи. Срок индексации зависит от ресурса и для некоторых сайтов может занимать довольно продолжительное время.

Выдвигающаяся форма поиска по клику

При адаптации сайта под самые маленькие разрешения устройств, хорошо иметь под рукой надежное решение, как размеры формы поиска свести к минимуму. Такое решение есть - это выдвигающаяся форма поиска при клике на иконку.

Как сделать выдвигающийся поиск по клику.

В обычном состоянии форма поиска свернута до минимального размера и только иконка указывает на то, что это форма поиска. При клике на иконку, поле ввода формы выдвигается.

Как сделать выдвигающийся поиск по клику.

HTML-код

В HTML разметке прописывается контейнер wrap с одним полем ввода input для текста и шрифтовой иконкой, код которой скопирован с Font Awesome. На официальном сайте Font Awesome, вы без труда найдете нужную иконку.

Между тегами head подключаем ссылку на файл иконочного шрифта и переходим к написанию стилей, чтобы форма смотрелась более привлекательно.

CSS-код

За счет нулевой ширины, поле ввода формы скрыто, мы видим только часть контейнера со скругленными углами - border-radius и с тенью box-shadow.

.wrap width: 0px;
border-radius: 7px;
box-shadow: 0 0 9px rgba(0,0,0,0.6);
>

В поле ввода input убираем рамки - border и дефолтный белый цвет через прозрачный фон - transparent. В нераскрытом состоянии форма спрятана - width: 0%.

.input border: 0;
background: transparent;
width: 0%;
>

Задаем белый цвет - color и размеры иконки - 22 пикселя через свойство font-size.

Позиционируем иконку относительно родителя - wrap.

position: absolute;
right: 17px;
top: 15px;

В активном состоянии контейнер раскрывается на ширину в 250 пикселей и благодаря transition делает это плавно.

.wrap.active width: 240px;
padding-left: 18px;
transition: all 0.6s ease;
>

Поле ввода в активном состоянии раскрывается на 98% по ширине относительно своего родителя.

.input.active width: 98%;
padding-left: 6px;
transition: all 0.4s 0.7s ease;
>

Атрибут placeholder выводит текст белого цвета "Поиск" в текстовом поле формы, который исчезает, как только пользователь вводит свое поисковое слово.

Итак, какой механизм будет выдвигать форму поиска при клике?

Метод toggleClass

Подключаем библиотеку jQuery перед закрывающим тегом body:

Создаем JavaScript файл и так же подключаем внизу HTML-файла:

Функция будет выполняться, как только DOM загрузится.

Область для клика - это иконка с классом fa-search.

Метод toggleClass работает как переключатель между классами оформления при клике. Если нет класса "active", то он его добавит и тогда форма поиска выдвинется. Если есть класс "active" - удалит и поисковая форма свернётся обратно.

Событие focus отслеживает текстовое поле input.

Посмотреть как выдвигается форма поиска и код целиком.


Если Вы не хотите пропустить новые материалы на сайте,
то Вы можете подписаться на обновления: Подписаться на обновления

Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

Порекомендуйте эту статью друзьям:

Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

Она выглядит вот так:

Комментарии ( 0 ):

После публикации вчерашней статьи по верстке поисковой формы меня раскритиковали, мол верстка отстой, есть же современные HTML5 и CSS3.

Пример верстки поисковой формы для сайта на HTML5 и CSS3

Я, конечно, понимаю, последние стандарты это круто и все такое. Но дело в том, что верстаю я, как правило, под заказ, а там в большинстве случаев важна полная идентичность в разных браузерах, что не позволяет использовать последние технологии. Поэтому я ориентируюсь в первую очередь на кроссбраузерность и поисковую форму по привычке сверстал «по-старому».

В общем, этим постом исправляю ситуацию (в угоду недовольным прошлой статьей =) и предлагаю свой вариант верстки той же самой поисковой формы, но уже с использованием технологий HTML5 и CSS3.

Пример того, что получится в результате, можно увидеть здесь.

Что мы теряем при верстке данной формы с помощью HTML5 и CSS3

  1. IE9 и ниже — не увидим текст по умолчанию (атрибут placeholder ).
  2. IE8 и ниже — не увидим закругленных углов и внутренних теней.
  3. IE7 — для него приходится указать другую ширину формы, т.к. он не поддерживает свойство box-sizing .
  4. IE6 — а его вообще в расчет не берем =)

В остальных современных браузерах все замечательно. Я считаю, что вышеуказанные недостатки не критичны, поэтому для своего сайта я бы смело использовал форму, сверстанную по последним технологиям.

HTML-код формы поиска

Выглядит он вот так:

По сравнению с формой из предыдущей статьи здесь внесены следующее изменения в соответствии с технологией HTML5:

  1. Атрибут type="text" заменен type="search" .
  2. Инлайновый скрипт заменен на placeholder="поиск" .

CSS-код

Вот все необходимые стили с комментариями:

И стили для IE ниже 9-й версии:

P.S. Спасибо критикам за комментарии к предыдущей статье! Благодаря вам, у меня в голове отложились некоторые новые для меня моменты по верстке.

Читайте также: