HTML Forms
Table of Contents + โ
In previous lessons we learned about HTML buttons and how to use them to perform actions on a web page. In this lesson, we will learn about HTML forms, which are essential for collecting user input on websites.
Now we will look into HTML Forms to collect user input as a form of data.
๐ What Are HTML Forms?
HTML forms are containers that collect user input and send it somewhere for processing. Every time you:
- Log into a website
- Search on Google
- Fill out a contact form
- Post on social media
- Make an online purchase
โฆyouโre using HTML forms!
๐ก Think of Forms Like...
Forms are like paper forms we fill out at the doctorโs office, but digital! They have fields for different types of information and a way to submit the data.
๐๏ธ Basic Form Structure
We use the <form> element to create a form.
๐๏ธ Basic Form Example
<form action="/submit" method="post"> <!-- Form controls go here --> <input type="text" name="username"> <button type="submit">Submit</button></form>๐ฏ Form Attributes:
In above example, we have below attributes:
action= Where to send the form data when submittedmethod= How to send the data (getorpost)
Also as you can see, we have used <input> and <button> elements inside the form. These are the controls that allow users to enter data for form and then submit it.
๐ง Additional Form Attributes:
There are some other useful attributes you can use with forms:
| Attribute | Description | Possible Values |
enctype | Specifies how the form data should be encoded when submitted (e.g., multipart/form-data for file uploads) | application/x-www-form-urlencoded, multipart/form-data, text/plain |
autocomplete | Controls whether the browser should autocomplete fields (e.g., on, off) | on, off |
novalidate | Disables HTML5 validation for the form |
๐ฏ Buttons and Form Submission
Buttons are important for submitting forms or performing actions. There are three types of buttons you can use in forms:
- Submit Button: Submits the form data to the server.
- Reset Button: Resets all form fields to their initial values.
- Regular Button: Can be used to trigger JavaScript functions or other actions.
<form> <!-- Submit button - submits the form --> <button type="submit">Submit Form</button>
<!-- Reset button - clears all form fields --> <button type="reset">Clear Form</button>
<!-- Regular button - does nothing by default --> <button type="button">Click Me</button></form>๐ Sign Up Form
We will now create a simple sign-up form that we could have seen on many websites like social media platforms, online stores, etc.
<form action="/signup" method="post"> <h2>Sign Up</h2>
<label for="username">Username:</label> <input type="text" id="username" name="username" required style="border: 1px solid #ccc; padding: 8px; width: 100%;" />
<label for="email">Email:</label> <input type="email" id="email" name="email" required style="border: 1px solid #ccc; padding: 8px; width: 100%;" />
<label for="password">Password:</label> <input type="password" id="password" name="password" required minlength="8" style="border: 1px solid #ccc; padding: 8px; width: 100%;" />
<button type="submit" style="background-color: #4CAF50; color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer;">Create Account</button> <button type="reset" style="background-color: #f44336; color: white; padding: 10px 15px; border: none; border-radius: 5px; cursor: pointer;">Clear</button> </form>the output of the above code will look like this:
Sign Up Form Output
Ignore the styles in the output, they are just added for better visibility of the form elements.
As you can see, we have used various input types like text, email, and password to collect user information. The required attribute ensures that users must fill out these fields before submitting the form. Also we have created two buttons, one for submitting the form and another for resetting the form fields.
โ Form Validation
HTML5 provides built-in form validation that we can use to ensure users enter the correct data.
๐ Required Fields
If we want to make sure that users fill out certain fields before submitting the form, we can use the required attribute:
<input type="text" name="name" required><input type="email" name="email" required>๐ Length Validation
We can also validate the length of input fields using minlength and maxlength attributes:
<input type="password" name="password" minlength="8" maxlength="20" required><textarea name="bio" maxlength="500"></textarea>๐ข Number Validation
We can also validate numeric inputs using type="number" along with min, max, and step attributes:
<input type="number" name="age" min="18" max="100" required><input type="range" name="rating" min="1" max="10" step="0.5">๐จ Pattern Validation (Regular Expressions)
We can also use the pattern attribute to match specific formats using regular expressions:
<!-- Phone number pattern --><input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" placeholder="123-456-7890" title="Please enter phone number in format: 123-456-7890">
<!-- Username pattern (letters and numbers only) --><input type="text" name="username" pattern="[a-zA-Z0-9]+" title="Username can only contain letters and numbers">๐ Custom Validation Messages
By default, browsers will show default validation messages based on the type of validation error. However, we can customize these messages using the title attribute as below:
<input type="email" name="email" required title="Please enter a valid email address">
<input type="password" name="password" minlength="8" required title="Password must be at least 8 characters long">๐จ Form Best Practices
โ Do This:
- Always use labels with proper
forattributes - Group related fields with
<fieldset>and<legend> - Use appropriate input types for better UX
- Provide clear error messages and validation
- Make required fields obvious with asterisks or labels
- Use placeholder text as hints, not labels
- Test forms on mobile devices
โ Avoid This:
- Using placeholder text instead of labels
- Making forms too long - break into steps if needed
- Asking for unnecessary information
- Using vague button text like โSubmitโ or โClick Hereโ
- Forgetting to validate on the server side
- Not providing feedback after form submission
๐ฏ Mobile-Friendly Forms
On mobile devices, the right input type can show the appropriate keyboard (numeric for phone numbers, email keyboard for emails, etc.). This greatly improves user experience!
๐ฎ Try It Yourself!
Create different types of forms with these exercises:
- Create a folder interactive-elements if not already created.
- Create a file named
forms.mdxinside theinteractive-elementsfolder. - Add a simple contact form with fields with below code:
<!DOCTYPE html><html><head> <title>Contact Us</title></head><body> <h1>Contact Us</h1>
<form action="/submit-contact" method="post" enctype="multipart/form-data">
<!-- Personal Information --> <fieldset> <legend>Personal Information</legend>
<label for="first-name">First Name: *</label> <input type="text" id="first-name" name="first_name" required>
<label for="last-name">Last Name: *</label> <input type="text" id="last-name" name="last_name" required>
<label for="email">Email Address: *</label> <input type="email" id="email" name="email" required>
<label for="phone">Phone Number:</label> <input type="tel" id="phone" name="phone" placeholder="(555) 123-4567">
<label for="company">Company:</label> <input type="text" id="company" name="company"> </fieldset>
<!-- Inquiry Details --> <fieldset> <legend>Inquiry Details</legend>
<label for="subject">Subject: *</label> <select id="subject" name="subject" required> <option value="">Please select a subject</option> <option value="general">General Inquiry</option> <option value="support">Technical Support</option> <option value="sales">Sales Question</option> <option value="partnership">Partnership Opportunity</option> <option value="other">Other</option> </select>
<label for="priority">Priority:</label> <input type="radio" id="low" name="priority" value="low" checked> <label for="low">Low</label>
<input type="radio" id="medium" name="priority" value="medium"> <label for="medium">Medium</label>
<input type="radio" id="high" name="priority" value="high"> <label for="high">High</label>
<label for="message">Message: *</label> <textarea id="message" name="message" rows="6" placeholder="Please describe your inquiry in detail..." maxlength="1000" required></textarea>
<label for="attachment">Attach File (optional):</label> <input type="file" id="attachment" name="attachment" accept=".pdf,.doc,.docx,.txt,.jpg,.png"> </fieldset>
<!-- Hidden fields --> <input type="hidden" name="form_id" value="contact_form_v1"> <input type="hidden" name="timestamp" value="2024-01-15">
<!-- Form submission --> <div> <button type="submit">Send Message</button> <button type="reset">Clear Form</button> </div>
<p><small>* Required fields</small></p> </form></body></html>And check how it looks in your browser. You can also add some styles to make it look better.
You may also create forms for:
-
A survey with multiple choice questions Fields like:
- Name
- Age
- Gender
- Feedback
-
A login form with username and password fields
๐ What Youโve Learned
Outstanding progress! You now know how to:
- โ Create form structures with proper elements
- โ Implement form validation with HTML5
- โ Follow form best practices for usability
Forms are essential for creating interactive websites that engage with users!