阿里云主机折上折
  • 微信号
Current Site:Index > `<select>` - dropdown selection box

`<select>` - dropdown selection box

Author:Chuan Chen 阅读数:6218人阅读 分类: HTML

The <select> tag in HTML is used to create dropdown selection boxes, allowing users to choose one or more values from a predefined list of options. It is typically used in conjunction with the <option> tag and supports features like single selection, multiple selection, and grouping. It is an essential component for form interactions.

Basic Usage of <select>

The simplest <select> structure consists of an outer <select> tag and multiple nested <option> tags. Each <option> represents a selectable item, where the value attribute is the data submitted to the server, and the text inside the tag is what the user sees.

<select>
  <option value="apple">Apple</option>
  <option value="banana">Banana</option>
  <option value="orange">Orange</option>
</select>

When the user selects "Banana," the submitted form data will be banana. If no value is specified, the text content of the option (e.g., "Banana") will be submitted instead.

Default Selection and Placeholder Options

The selected attribute can be used to set a default selected option. To include a placeholder option with no default value (e.g., "Please select"), add a disabled and hidden option:

<select>
  <option value="" disabled selected hidden>Please select a fruit</option>
  <option value="apple">Apple</option>
  <option value="banana" selected>Banana</option>
  <option value="orange">Orange</option>
</select>

Multiple Selection

Adding the multiple attribute allows users to select multiple options by holding the Ctrl (Windows) or Command (Mac) key. In this case, the <select> will appear as a scrollable list:

<select multiple>
  <option value="red">Red</option>
  <option value="green">Green</option>
  <option value="blue">Blue</option>
</select>

Option Grouping

Use <optgroup> to group options logically, with the label attribute defining the group name:

<select>
  <optgroup label="Fruits">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
  </optgroup>
  <optgroup label="Vegetables">
    <option value="carrot">Carrot</option>
    <option value="tomato">Tomato</option>
  </optgroup>
</select>

Dynamic Manipulation and JavaScript Interaction

JavaScript can dynamically modify the content of <select>. For example, loading a list of cities based on the user's selected country:

<select id="country">
  <option value="china">China</option>
  <option value="usa">USA</option>
</select>
<select id="city"></select>

<script>
  const countrySelect = document.getElementById('country');
  const citySelect = document.getElementById('city');
  
  const cities = {
    china: ['Beijing', 'Shanghai', 'Guangzhou'],
    usa: ['New York', 'Los Angeles', 'Chicago']
  };

  countrySelect.addEventListener('change', () => {
    const selectedCountry = countrySelect.value;
    citySelect.innerHTML = cities[selectedCountry]
      .map(city => `<option value="${city}">${city}</option>`)
      .join('');
  });
</script>

Styling Customization and Limitations

The default appearance of <select> is limited by the operating system, but partial customization is possible with CSS. The following example removes the default arrow and adds custom styling:

<style>
  .custom-select {
    appearance: none;
    padding: 8px 30px 8px 10px;
    border: 1px solid #ccc;
    border-radius: 4px;
    background: url('data:image/svg+xml;utf8,<svg fill="black" viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/></svg>') no-repeat right 10px center;
  }
</style>

<select class="custom-select">
  <option value="volvo">Volvo</option>
  <option value="saab">Saab</option>
</select>

Accessibility Recommendations

To improve accessibility:

  1. Associate with <label> tags:
    <label for="fruit-select">Select a fruit:</label>
    <select id="fruit-select">
      <option value="apple">Apple</option>
    </select>
    
  2. Provide explanations for disabled states:
    <select aria-disabled="true" disabled>
      <option>Currently unavailable</option>
    </select>
    

Practical Use Cases

Form Submission

<form action="/submit" method="post">
  <label for="size">Select size:</label>
  <select id="size" name="size">
    <option value="s">Small</option>
    <option value="m">Medium</option>
  </select>
  <button type="submit">Submit</button>
</form>

Dynamic Filtering

Combine with input to implement search filtering:

<input type="text" id="search" placeholder="Search...">
<select id="items" size="5">
  <option value="1">JavaScript</option>
  <option value="2">HTML</option>
</select>

<script>
  document.getElementById('search').addEventListener('input', (e) => {
    const term = e.target.value.toLowerCase();
    Array.from(document.getElementById('items').options).forEach(option => {
      option.hidden = !option.text.toLowerCase().includes(term);
    });
  });
</script>

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.