Тег SELECT

Html select chosen option

Один пункт в раскрывающемся списке .

Время чтения: меньше 5 мин

Кратко

Скопировать ссылку «Кратко» Скопировано

Тег используется в интерактивных элементах управления для вёрстки одиночного пункта списка.

Пример

Скопировать ссылку «Пример» Скопировано

              form> label for="city-select">Ваш городlabel> select name="city" id="city-select"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select> form>      

Подробно

Скопировать ссылку «Подробно» Скопировано

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

Атрибуты

Скопировать ссылку «Атрибуты» Скопировано

disabled

Скопировать ссылку «disabled» Скопировано

Атрибут булевого типа. Если задан, то пункт списка нельзя выбрать. Часто браузеры выделяют такой элемент управления серым цветом, и на нём не срабатывают события клика или фокуса. Даже если атрибут не задан, элемент всё равно может быть отключён, если находится внутри тега с заданным атрибутом disabled .

           select name="city1"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara" disabled>Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      

label

Скопировать ссылку «label» Скопировано

Значение этого атрибута задаёт текст пункта в списке. Если атрибут не задан, то в качестве значения берётся текстовое содержимое тега .

        select name="city2"> option value="petersburg" selected label="Ленинград">Санкт-Петербургoption> option value="samara" label="Куйбышев">Самараoption> option value="volgograd" label="Сталинград">Волгоградoption> option value="ekaterinburg" label="Свердловск">Екатеринбургoption> select>      

Несмотря на то, что задано текстовое содержимое тега , в выпадающем списке отображаются значения из атрибутов label :

selected

Скопировать ссылку «selected» Скопировано

           select name="city3"> option value="">-- Выберите город --option> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan" selected>Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      
          select name="city4" multiple size="6"> option value="petersburg">Санкт-Петербургoption> option value="moscow" selected>Москваoption> option value="kazan" >Казаньoption> option value="samara" selected>Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      

value

Скопировать ссылку «value» Скопировано

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

На практике

Скопировать ссылку «На практике» Скопировано

Денис Ежков советует

Скопировать ссылку «Денис Ежков советует» Скопировано

🛠 Раньше браузеры не предоставляли никаких средств для нормальной стилизации элемента , и это доставляло очень много головной боли фронтенд-разработчикам 🙁 Стиль элементов можно было поменять, только если тегу был задан атрибут multiple . Тогда список целиком становился частью потока страницы, и мы имели возможность применять стили к его элементам. Вот как выглядело решение:

          select name="city" id="city-select" multiple> option value="petersburg">Санкт-Петербургoption> option value="moscow">Москваoption> option value="kazan">Казаньoption> option value="samara">Самараoption> option value="perm">Пермьoption> option value="novosibirsk">Новосибирскoption> select>      
 select  counter-reset: cnt;> option:nth-child(2n)  background-color: #282a2e;> option  counter-increment: cnt;> option::before  content: counter(cnt) ". ";> select  counter-reset: cnt; > option:nth-child(2n)  background-color: #282a2e; > option  counter-increment: cnt; > option::before  content: counter(cnt) ". "; >      

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

В Safari стилизация для доступна не полностью, даже если тег имеет атрибут multiple .

Источник

Html select chosen option

Тег позволяет создать элемент интерфейса в виде раскрывающегося списка, а также список с одним или множественным выбором, как показано далее. Конечный вид зависит от использования атрибута size тега , который устанавливает высоту списка. Ширина списка определяется самым широким текстом, указанным в теге , а также может изменяться с помощью стилей. Каждый пункт создается с помощью тега , который должен быть вложен в контейнер . Если планируется отправлять данные списка на сервер, то требуется поместить элемент внутрь формы. Это также необходимо, когда к данным списка идет обращение через скрипты.

Список множественного выбора Раскрывающийся список

Синтаксис

Атрибуты

accesskey Позволяет перейти к списку с помощью некоторого сочетания клавиш. autofocus Устанавливает, что список получает фокус после загрузки страницы. disabled Блокирует доступ и изменение элемента. form Связывает список с формой. multiple Позволяет одновременно выбирать сразу несколько элементов списка. name Имя элемента для отправки на сервер или обращения через скрипты. required Список обязателен для выбора перед отправкой формы. size Количество отображаемых строк списка. tabindex Определяет последовательность перехода между элементами при нажатии на клавишу Tab

Также для этого тега доступны универсальные атрибуты и события.

Закрывающий тег

       

Источник

HTML Select Tag – How to Make a Dropdown Menu or Combo List

Kolade Chris

Kolade Chris

HTML Select Tag – How to Make a Dropdown Menu or Combo List

You use the HTML select tag to create drop-down menus so that users can select the value they want. It is an instrumental feature in collecting data to be sent to a server.

The select tag normally goes within a form element, with the items to choose from coded within another tag, . It can also be a standalone element, which would still be associated with a form with one of its special attributes, form .

In this tutorial, I will walk you through how to create a dropdown menu with the select tag so you can start using it to collect data in your coding projects. I will also touch on how to style the select tag because it is notoriously difficult to style.

Here’s an Interactive Scrim about How to Make a Dropdown Menu or Combo List in HTML

Attributes of the Select Tag

Before I dive deep into whot to create a dropdown menu with the select tag, we need to discuss the attributes the select tag takes.

  • name: You need to attach the name to every form control as it is used to reference the data after it’s submitted to the server.
  • multiple: This attribute lets the user select multiple options from the dropdown menu.
  • required: This is typically used for validation. With it, the form won’t submit unless a user selects at least one option from the dropdown.
  • disabled: This attribute stops the user from interacting with the options.
  • size: Expressed in numbers, the size attribute is used to specify how many options will be visible at a time.
  • autofocus: This attribute is used on all form inputs, select inclusive, to specify that the input should be on focus when the page loads.

How to Create a Dropdown Menu with the Select Tag

To create a dropdown menu with the select tag, you firstly need a form element. This is because you will also have a submit button within it (the form element) in order to submit the data to the server.

 

I’ve added some simple CSS to center the dropdown and button, and give the body a light-grey background:

To make it more elaborate and accessible, you can also attach the select box to a label element, so it gets focused when the label text is clicked. You can do that with this code:

 

I put a number symbol (#) as a the value of the action attribute so you don’t get a 404 when you click on the submit button.

But now we have to make a little change in the CSS:

In the end, this is the result:

It doesn’t end there. One of the dropdown items appears by default and will be selected if the user clicks on the submit button immediately when they land on the page.

But this isn’t a good user experience. You can get rid of it by coding in “select a language” as the first item of the dropdown.

  

When the user clicks the select box to select an item, the dropdown is also covering the submit button – another thing that negatively affects good user experience.

You can change this with the size attribute, which will show a certain number of items by default and show a scroll for other items in the dropdown.

This also lets you get rid of the dummy first item, because some of the items will be visible to the user automatically.

  

With the multiple attribute, you can allow the user to select multiple items from the dropdown.

  

This makes 4 items visible by default. To select multiple items, the user has to hold down the shift or ctrl key, then select with the mouse.

That’s not all you can do with the select and tags. You can also make a multi-layer select box with the element inside a tag.

You can convert the already made dropdown to a multi-layer select box like this:

 

multi-select

How to Style the Select Element

Styling the select element is often confusing and renders inconsistently within browsers. But you can always try the following:

  

In the CSS code snippet above, I gave the text in the select box the following appearance:

  • a font family of cursive and a color of white,
  • an outline of 0 to remove the ugly outline when it is on focus,
  • a greenish background,
  • a 1-pixel tick crimson-colored border,
  • a border-radius of 4 pixels to get a slightly rounded border on all sides,
  • and a padding of 4 pixels to space things out a little bit.

The select box now looks better:

Conclusion

The select tag is very useful when you’re making dropdowns and combo lists in HTML. It is like a radio button and checkbox in one package.

Remember that with radio buttons, you only get to select one item from a list – but with a checkbox, you can select multiple items. Select is more flexible, as you can configure it to accept only a single item or multiple items.

One issue with the select tag is that it is very difficult to style. A reasonable solution is to use a CSS library that offers great utility classes to style a form along with the select element.

I hope this tutorial has made you more familiar with the select tag so you can start using it in your projects.

Thank you for reading and keep coding.

Источник

Читайте также:  El html que es
Оцените статью