Select lists and multi-line text
Not all data is convenient to type into a single-line field. When there are many options and the valid answers are known in advance, it is easier for a person to pick from a list. And a review or a comment needs a field with several lines.
A dropdown list
<select> creates a dropdown list, and each option is wrapped in <option>:
<select>
<option>London</option>
<option>Berlin</option>
<option>Lisbon</option>
</select>Click the list — the options open. The first one is selected until the user picks another.
Value and default choice
The value attribute of <option> is what gets sent to the server. The person sees clear text, and the server receives a short code. selected picks an option in advance:
<label>
City
<select name="city">
<option value="lon">London</option>
<option value="ber" selected>Berlin</option>
<option value="lis">Lisbon</option>
</select>
</label>On submit the form sends city=ber. As with any field, the caption is made with <label>.
Option groups
A long list is easier to read when split into groups with the <optgroup> tag. The group name is set by the label attribute, and it cannot be selected:
<select name="drink">
<optgroup label="Coffee">
<option>Espresso</option>
<option>Cappuccino</option>
</optgroup>
<optgroup label="Tea">
<option>Green</option>
<option>Black</option>
</optgroup>
</select>Several options
The multiple attribute allows choosing several items — while holding Ctrl (Cmd on a Mac). The list is then shown open, and size sets the number of visible rows:
<select name="toppings" multiple size="4">
<option>Cinnamon</option>
<option>Syrup</option>
<option>Whipped cream</option>
<option>Chocolate</option>
</select>Such a list is awkward on phones, so for a few options checkboxes work better.
Multi-line text
<textarea> is a field with several lines. rows sets the height in lines, cols sets the width in characters. Unlike <input>, this tag is paired:
<label for="review">Your review</label><br>
<textarea id="review" name="review" rows="4" cols="40"></textarea>Drag the bottom-right corner — the field resizes.
Suggestions while typing
<datalist> gives a field a list of suggestions but still lets you type your own value. It is linked to the field with the list attribute:
<label>Favourite drink <input list="drinks" name="drink"></label>
<datalist id="drinks">
<option value="Cappuccino">
<option value="Latte">
<option value="Flat white">
</datalist>Common mistake
<textarea> has no value attribute: the initial text goes between the tags. And everything between them — including spaces and line breaks added to make the code look nice — ends up in the field:
<textarea rows="3">
This text has extra spaces before it and an empty line after it
</textarea>
<textarea rows="3">This one starts on the first line</textarea>Put the closing tag right after the text, and write an empty field as <textarea></textarea> with nothing inside.