HTML Forms

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 submitted
  • method = How to send the data (get or post)

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:

  1. Submit Button: Submits the form data to the server.
  2. Reset Button: Resets all form fields to their initial values.
  3. 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

Sign Up

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:

  1. Always use labels with proper for attributes
  2. Group related fields with <fieldset> and <legend>
  3. Use appropriate input types for better UX
  4. Provide clear error messages and validation
  5. Make required fields obvious with asterisks or labels
  6. Use placeholder text as hints, not labels
  7. Test forms on mobile devices

โŒ Avoid This:

  1. Using placeholder text instead of labels
  2. Making forms too long - break into steps if needed
  3. Asking for unnecessary information
  4. Using vague button text like โ€œSubmitโ€ or โ€œClick Hereโ€
  5. Forgetting to validate on the server side
  6. 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:

  1. Create a folder interactive-elements if not already created.
  2. Create a file named forms.mdx inside the interactive-elements folder.
  3. 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:

  1. A survey with multiple choice questions Fields like:

    • Name
    • Email
    • Age
    • Gender
    • Feedback
  2. 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!

Share & Connect