HTML Forms
π¨ Introduction to HTML Forms
HTML forms are used to collect user input on web pages. They are essential for things like login screens, contact forms, surveys, and more. Forms can include text fields, radio buttons, checkboxes, dropdowns, and submit buttons. π
>>βForms are the bridge between your users and your application.β π
π§± Basic Form Structure
Basic HTML Form
<form action="/submit" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name" />
<br />
<label for="email">Email:</label>
<input type="email" id="email" name="email" />
<br />
<input type="submit" value="Submit" />
</form>Note
π‘ The action attribute defines where the form data should be sent. The method defines how it's sent β usually GET or POST.
π§© Common Form Elements
- <input> β Text field, password, checkbox, radio, etc.
- <textarea> β Multi-line text input
- <select> β Dropdown list
- <label> β Describes inputs for accessibility
- <button> or <input type="submit"> β Submit forms
π Input Types
Various Input Types
<input type="text" /> <!-- Single-line input -->
<input type="email" /> <!-- Email validation -->
<input type="password" /> <!-- Hidden input for passwords -->
<input type="radio" /> <!-- Single choice -->
<input type="checkbox" /> <!-- Multiple choice -->
<input type="date" /> <!-- Date picker -->
<input type="submit" /> <!-- Submit button -->π¦ Textarea Element
Textarea Example
<label for="message">Your Message:</label>
<textarea id="message" name="message" rows="4" cols="30">
Enter your message here...
</textarea>β¬οΈ Select Dropdown
Select Dropdown Example
<label for="fruit">Choose a fruit:</label>
<select id="fruit" name="fruit">
<option value="apple">Apple</option>
<option value="banana">Banana</option>
<option value="cherry">Cherry</option>
</select>Note
π§ Always use the <label> element with for to improve accessibility and form usability.
π― Form Submission
Forms can be submitted either via GET (appends data to URL) or POST (sends data in request body). Use POST for sensitive information.
| Method | When to Use |
|---|---|
| GET | Search queries, filtering, bookmarking |
| POST | Login, forms with sensitive data |
β Form Best Practices
- βοΈ Use label for accessibility
- βοΈ Always validate input on both client and server
- βοΈ Use semantic type values for better UX
- βοΈ Add placeholder for hinting input expectations
π Form Validation (Client-side)
Required Field Validation
<input type="email" name="email" required />Note
β οΈ Client-side validation is helpful but should not replace secure server-side validation.
π Additional Resources
>>βForms are not just inputsβtheyβre conversations with your users.β π¬