HTML - Select Element

About

select is an HTML element that creates a drop-down list used in a form

Structure

Inside a select, you may find:

  • an optgroup [optional] that group
    • option elements that defines the values.

Example

Option

Only with option has children.

For example, this HTML creates a drop-down list of colors:

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

OptGroup

HTML - Optgroup element (Group of Option)

<form onSubmit="handleSubmit(event)">
<label for="country">Choose a country:</label>
<select id="country">
    <optgroup label="Europa">
        <option>England</option>
        <option>Germany</option>
        <option>Netherland</option>
    </optgroup>
    <optgroup label="Africa">
        <option>Marroco</option>
        <option>Algeria</option>
        <option>Tunisia</option>
    </optgroup>
</select>
<button type="submit">Submit form</button>
</form>
let handleSubmit = function(event){
    event.preventDefault();
    console.log("The country chosen is "+event.target.country.value);
}

Attribute

Multiple

Boolean attribute indicates that multiple options can be selected in the list by holding the ctrl key (Default: false)

Example:

  • the HTML
<form onSubmit="handleSubmit(event);" >
    <select id="color" name="color" multiple>
      <option value="blue">Blue</option>
      <option selected value="yellow">yellow</option>
      <option value="red">Red</option>
      <option selected value="green">Green</option>
    </select>
    <button type="submit">Submit form</button>
</form>
let handleSubmit = function(event){
    event.preventDefault();
    // event.target is the form
    // event.target.color is the select
    console.log("The select type is "+event.target.color.type);
    console.log("The number of options are "+event.target.color.length);
    console.log("The first value chosen is "+event.target.color.value);
    let formData =  new FormData(event.target);
    let colors =  formData.getAll("color");
    console.log("The value chosen are "+colors);
}
  • The result

Form

If not used in a form element, you can set the form attribute with the id of the form to associate it with the select.

Library

Documentation / Reference


Powered by ComboStrap