While the <input> tag handles many common scenarios, other dedicated elements are required for more complex user inputs, such as large blocks of text or selections from a long list.
1. Multi-Line Text Input (<textarea>)
The <textarea> element is used to create a multi-line input field, suitable for comments, messages, or detailed feedback.
- Non-Void Element: Unlike
<input>,<textarea>is not a void element and requires both an opening and closing tag. The text placed between the tags serves as the initial value. - Attributes: It requires the
nameattribute for submission and often usesrowsandcolsto define its initial visible size (though CSS is better for styling).
<label for="comments">Your Feedback:</label>
<textarea id="comments" name="user_feedback" rows="5" cols="40" placeholder="Type your message here..."></textarea>
2. Drop-Down Lists (<select>, <option>)
The <select> element is used to create a drop-down menu or list box, allowing the user to select one or more options from a pre-defined list.
- Container: The
<select>tag creates the drop-down box itself, requiring thenameattribute. - Items: Each item in the list is defined by an
<option>tag. - Data Value: The
valueattribute on the<option>tag is the data sent to the server. The text between the tags is what the user sees.
<label for="country">Select Country:</label>
<select id="country" name="destination_country">
<option value="US">United States</option>
<option value="CA">Canada</option>
<option value="UK" selected>United Kingdom</option>
</select>
A. The selected Attribute
Adding the boolean attribute selected to an <option> tag makes that choice the default value when the page loads.
3. Option Grouping (<optgroup>)
For long drop-down lists, you can group related options using the <optgroup> tag. This element requires the label attribute, which is displayed as an unselectable heading within the menu.
<select name="city">
<optgroup label="North America">
<option value="ny">New York</option>
<option value="to">Toronto</option>
</optgroup>
<optgroup label="Europe">
<option value="pa">Paris</option>
<option value="be">Berlin</option>
</optgroup>
</select>
4. Input Grouping (<fieldset> and <legend>)
To improve the structure and accessibility of complex forms, related inputs can be grouped together using the <fieldset> element.
- Container:
<fieldset>draws a box around the grouped controls. - Title: The
<legend>element provides a title or caption for the fieldset group.
<form action="/checkout" method="POST">
<fieldset>
<legend>Contact Information</legend>
<label for="fname">First Name:</label>
<input type="text" id="fname" name="first_name">
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="user_phone">
</fieldset>
<button type="submit">Submit</button>
</form>
