select is an HTML control form element used for selecting one or more value amongst a set of options.
It creates a drop-down list used in a form that will set a scalar value from a list of options.
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>
HTML - Optgroup element (Group of Option)
<form onSubmit="handleSubmit(this); return false;">
<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(form){
console.log("The country chosen is "+form.country.value);
}
By default, there is no free form. The select element forces a selection (whereas datalist does not)
But you may add an extra input value
<label for="color">Colors:</label>
<select>
<option value="blue">Blue</option>
<option value="yellow">yellow</option>
<option value="red">Red</option>
<option selected value="green">Green</option>
</select>
If other, please specify:
<input type="text" name="color_free" id="color_free">
Inside a select, you may find:
Boolean attribute indicates that multiple options can be selected in the list by holding the ctrl key (Default: false)
Example:
<form onSubmit="handleSubmit(this); return false;" >
<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(form){
console.log("The select type is "+form.color.type);
console.log("The number of options are "+form.color.length);
console.log("The first value chosen is "+form.color.value);
let formData = new FormData(event.target);
let colors = formData.getAll("color");
console.log("The value chosen are "+colors);
}
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.
When the value changes, it fires an input event.
<select name="crust">
<option value="regular">Regular crust</option>
<option selected value="deep">Deep dish</option>
<option value="thin">Thin crust</option>
</select>
document.querySelector("select").addEventListener("input", function(){
console.log("The input event has fired for the value: "+this.value);
});
See also React Select Library