Forms and Inputs
Learn about form elements, attributes, advanced inputs, and validation in HTML.
Form Basics
Forms in HTML are used to collect user input. They contain interactive elements like text fields, buttons, and dropdowns.
Essential Form Elements
<form>
: Defines the form.<input>
: Creates input fields.<textarea>
: Allows multi-line text input.<button>
: Submits the form.<select>
and<option>
: Creates dropdowns.
Example:
<form action="submit.php" method="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="message">Message:</label>
<textarea id="message" name="message"></textarea>
<button type="submit">Submit</button>
</form>
Form Attributes
action
: Specifies where form data should be sent.method
: Defines the request method (GET
orPOST
).target
: Opens the response in a new window or tab (_blank
).novalidate
: Disables form validation.
Example:
<form action="/submit" method="post" target="_blank" novalidate>
<input type="text" name="username">
<button type="submit">Send</button>
</form>
Inputs
Common Input Types
email
: Validates email format.number
: Accepts only numeric values.date
: Provides a date picker.range
: Creates a slider.color
: Opens a color picker.file
: Allows file uploads.
Example:
<form>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required>
<label for="quantity">Quantity:</label>
<input type="number" id="quantity" name="quantity" min="1" max="10">
<label for="dob">Date of Birth:</label>
<input type="date" id="dob" name="dob">
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100">
<label for="favcolor">Favorite Color:</label>
<input type="color" id="favcolor" name="favcolor">
<label for="file">Upload File:</label>
<input type="file" id="file" name="file">
<button type="submit">Submit</button>
</form>
Validation Attributes
required
: Makes input mandatory.min
&max
: Defines numeric limits.pattern
: Specifies a regex pattern.step
: Sets the increment for numeric inputs.
Example:
<form>
<label for="phone">Phone Number:</label>
<input type="tel" id="phone" name="phone" pattern="[0-9]{10}" required>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="60" required>
<label for="price">Price:</label>
<input type="number" id="price" name="price" step="0.01">
<button type="submit">Submit</button>
</form>
Understanding these attributes ensures better user input handling and improved form usability.