Section 19: Select, Option, Optgroup, Textarea and Datalist
Learning Objectives
- Create dropdowns using select and option.
- Group options using optgroup.
- Collect longer text using textarea.
- Provide suggestions using datalist.
- Understand multiple and size attributes.
1. The select Element
Use select when users need to choose from a predefined list of options.
<label for="country">Country</label>
<select id="country" name="country" required>
<option value="">Choose a country</option>
<option value="in">India</option>
<option value="us">United States</option>
<option value="uk">United Kingdom</option>
</select>The empty first option acts as a prompt. With required on a normal single-select control, the empty value prevents the user from satisfying the field by leaving the prompt selected.
2. Option Values
<select name="department">
<option value="dev">Development</option>
<option value="qa">Quality Assurance</option>
<option value="hr">Human Resources</option>
</select>The value attribute is what is normally submitted. When value is omitted, the option's text is generally used as its value.
3. Grouping with optgroup
<label for="course">Choose a course</label>
<select id="course" name="course">
<optgroup label="Frontend">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="js">JavaScript</option>
</optgroup>
<optgroup label="Backend">
<option value="php">PHP</option>
<option value="node">Node.js</option>
</optgroup>
</select>4. Multiple Selections
<label for="skills">Skills</label>
<select id="skills" name="skills[]" multiple size="4">
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="laravel">Laravel</option>
<option value="node">Node.js</option>
</select>The multiple attribute allows more than one option to be selected. The name skills[] is a common server-side naming convention for a collection of values; the brackets are not required by HTML itself.
5. The textarea Element
Use textarea for longer text such as comments, addresses and messages.
<label for="message">Your Message</label>
<textarea id="message" name="message" rows="5" cols="40"
maxlength="1000" placeholder="Write your message here"></textarea>Unlike input, textarea has an opening and closing tag. Its initial text, if any, belongs between those tags, not in a value attribute.
6. The datalist Element
Datalist provides suggestions for an input. Unlike a select element, users can usually enter a value that is not in the suggestions.
<label for="framework">Framework</label>
<input id="framework" name="framework" list="framework-options">
<datalist id="framework-options">
<option value="Laravel">
<option value="React">
<option value="Vue.js">
<option value="Express">
</datalist>7. Which Control Should You Use?
- select: when users should choose from a defined list.
- textarea: when users need to enter longer text.
- datalist: when suggestions are useful but custom input should remain possible.