HTML Forms
An HTML form is used to collect user input. The user input is most often sent to a server for processing.
The <form> Element
The HTML <form> element is used to create an HTML form for user input:
<form>
<!-- form elements here -->
</form>
Form Attributes
| Attribute | Description |
|---|---|
action | URL where data is sent |
method | GET or POST |
enctype | Encoding type (for file uploads) |
autocomplete | on/off |
novalidate | Skip validation |
The <input> Element
The <input> element is the most used form element. It can be displayed in many ways depending on the type attribute:
<form action="/submit" method="post">
<!-- Text input -->
<label for="name">Name:</label>
<input type="text" id="name" name="name" placeholder="Enter name" required>
<!-- Email -->
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<!-- Password -->
<label for="pwd">Password:</label>
<input type="password" id="pwd" name="pwd" minlength="8">
<!-- Number -->
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="1" max="120">
<!-- Date -->
<input type="date" name="birthday">
<!-- Checkbox -->
<input type="checkbox" id="agree" name="agree">
<label for="agree">I agree to terms</label>
<!-- Radio buttons -->
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<!-- Submit -->
<input type="submit" value="Submit">
</form>
Select Dropdown
<label for="lang">Choose a language:</label>
<select id="lang" name="language">
<option value="">-- Select --</option>
<option value="html">HTML</option>
<option value="css">CSS</option>
<option value="js" selected>JavaScript</option>
</select>
Textarea
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50"
placeholder="Type your message..."></textarea>
HTML5 Form Validation
HTML5 added built-in form validation:
<input type="email" required> <!-- Must be filled -->
<input type="text" minlength="3"> <!-- Min 3 characters -->
<input type="number" min="0" max="100"> <!-- Number range -->
<input type="text" pattern="[A-Z]{3}"> <!-- Regex pattern -->