Skip to content

Understanding HTML Forms, with Examples

HTML Forms: A Comprehensive Guide with Examples

HTML forms are an essential part of nearly every website you encounter on a daily basis. Whether you‘re entering your shipping information to complete an online purchase, filling out a survey, or registering for an event, HTML forms enable websites to collect all sorts of data and user input.

For web developers, understanding how to create HTML forms is a fundamental skill. Forms act as the bridge between users interacting with a website and the website processing and storing that data on the backend. In this in-depth guide, we‘ll cover everything you need to know about HTML forms, from basic syntax to advanced techniques. Let‘s dive in!

The Anatomy of an HTML Form
At their core, HTML forms consist of two key parts:

  1. The
    element, which contains all the input fields and defines where and how the form data will be submitted
  2. The various form input elements, like text boxes, radio buttons, checkboxes, and more

Here‘s a basic example of an HTML form:




Let‘s break this down:

  • The
    tag has two important attributes:

    • action specifies where the form data will be sent when submitted (in this case, to a URL path of "/submit-form")
    • method specifies the HTTP method used to submit the form data (either "get" or "post")
  • Inside the form, we have two elements, one for a name and one for an email address
    • The type attribute defines what type of input it is (text and email)
    • The name attribute gives the input a name that will be associated with its value when the form is submitted
    • Matching for and id attributes link the inputs to their corresponding
  • The last is a submit button which the user clicks to submit the filled out form

This is just a simple example, but it demonstrates the key building blocks that make up an HTML form. Now let‘s look at some of the most commonly used form input types.

Common HTML Form Input Types
There are many different types of inputs you can use inside a

element. Here are some of the most common:

  • text – A single-line text field
  • number – A field for entering a number
  • password – Masks the characters entered into a single-line text field
  • email – A field that requires an @ character
  • url – A field that requires a valid URL
  • tel – For entering a telephone number
  • date – Displays a date picker for selecting a date
  • radio – A single selection within a group of choices
  • checkbox – Allows multiple selections from a group of choices
  • select – A dropdown menu of options
  • textarea – A multi-line text input
  • button – A clickable button (mostly used with JavaScript)

For many of these, the form will automatically validate the format of the entered data before allowing submission. For example, an email input requires an @ symbol, a url input requires a valid web address format, and a number input won‘t allow non-numeric characters.

Here‘s an example demonstrating a few of these input types:










This form includes:

  • A number input with min and max attributes to limit the allowed value
  • A tel input with a pattern attribute requiring a ###-###-#### phone number format
  • Checkboxes allowing the user to select multiple values
  • Labels describing each input‘s purpose

By leveraging the variety of input types, you can create forms to collect virtually any type of structured data from users. But in order for a form to be truly useful, you need to specify what happens when it‘s submitted.

Sending Form Data with Action and Method
The two most important attributes of the

tag itself are action and method. These define where the form data is sent and how it‘s sent when the form is submitted.

The action attribute contains a URL that processes the form submission. This often points to a server-side script (written in a language like PHP, Python, Ruby, etc.) that can read the form data and take some action, like adding it to a database, sending an email, or generating a response page.

The method attribute specifies which HTTP method should be used to submit the form data to the action URL. The two possible values are:

  • get (default) – Appends the form data to the URL specified in action. Best for searches and other requests that don‘t modify data.
  • post – Sends the form data in the body of the HTTP request to the action URL. Best for submitting sensitive data or making changes to a database.

In general, use get for retrieving data and post for sending data that gets stored or triggers an action. Here‘s an example putting the action and method attributes into practice:




When this form is submitted, it will send a POST request to https://example.com/login containing the entered username and password in the request body. The server can then check the credentials and respond accordingly (logging the user in if they‘re valid).

Styling HTML Forms with CSS
By default, browsers render form elements with a very plain, boxy appearance. But you can completely customize the look and layout of your forms using CSS. Common properties to adjust include:

  • width and height – Set the size of inputs and buttons
  • padding and margin – Adjust spacing inside and outside elements
  • border – Add borders of various styles and colors
  • background-color and color – Change background and text colors
  • font – Style labels and button text

Here‘s a simple example of styling an HTML form with CSS:

form {
width: 400px;
padding: 20px;
border: 1px solid #ccc;
border-radius: 5px;
background-color: #f4f4f4;
}

label, input {
display: block;
margin-bottom: 10px;
}

input[type="submit"] {
width: 100%;
padding: 10px;
border: none;
border-radius: 5px;
background-color: #4CAF50;
color: white;
cursor: pointer;
}






This CSS:

  • Sets the form to a fixed width with padding and a border
  • Spaces out the labels and inputs vertically
  • Makes the submit button span the full width of the form with custom colors

With some creativity, you can use CSS to make your forms match the design of your site and provide a better user experience. But there‘s another critical aspect to consider: accessibility.

Making Forms Accessible
It‘s important that your HTML forms are usable by everyone, including people with disabilities who rely on assistive technologies like screen readers. Some key accessibility considerations include:

  • Always use
  • Logically group related inputs with
    and

    elements

    • Provides context and makes long forms easier to navigate
  • Avoid using placeholder text as a replacement for labels
    • Placeholder text disappears when the input is focused, leaving no label
  • Ensure form elements can be navigated and controlled with a keyboard alone
    • All functionality should work without a mouse

Here‘s an example putting some of these accessibility features into practice:

Contact Info
<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>

<label for="phone">Phone:</label>  
<input type="tel" id="phone" name="phone"><br>
Message
<label for="subject">Subject:</label>
<input type="text" id="subject" name="subject"><br>

<label for="message">Message:</label>
<textarea id="message" name="message" rows="5"></textarea>


The key accessibility features include:

  • Using
    and

    to group related inputs
  • Associating each input with a
  • No placeholder text used as a replacement for visible labels

Building your forms with accessibility in mind from the start makes them usable by a wider audience and also tends to make the code more semantic and maintainable.

Enhancing Forms with JavaScript
While HTML forms can submit data to a server on their own, you can use JavaScript to add all sorts of extra functionality and interactivity. Some examples include:

  • Validating form data before submission to catch errors early
  • Showing or hiding form sections conditionally based on previous input
  • Enabling autocomplete for common inputs like addresses
  • Submitting form data asynchronously without reloading the page
  • Displaying a confirmation message or redirecting after successful submission

Here‘s a simple example of using JavaScript to validate an email field:






const email = document.getElementById(‘email‘);
const emailError = document.getElementById(‘email-error‘);

email.addEventListener(‘input‘, function () {
if (!email.validity.valid) {
emailError.textContent = ‘Please enter a valid email address‘;
} else {
emailError.textContent = ‘‘;
}
});

This script:

  1. Gets references to the email input and error message span
  2. Listens for changes to the email input value
  3. Checks if the entered email is valid using the input‘s built-in validity property
  4. Displays an error message if the email is invalid, or clears the error if valid

By combining HTML forms with JavaScript, you can create highly interactive experiences and offload work from your server to the user‘s browser. But HTML forms might be overkill for simpler data collection needs.

Alternatives to Coding HTML Forms
If you just need a quick way to collect data without building custom HTML forms, there are various no-code options available. One of the most popular is Google Forms.

With Google Forms, you can create online surveys and questionnaires using a simple web interface. You can add different question types (multiple choice, checkboxes, short answer, etc.), customize the form‘s appearance with themes and images, and collect responses in a Google Sheets spreadsheet.

Here‘s an example of what a Google Form might look like:

[Example Google Form screenshot]

To get started with Google Forms:

  1. Go to https://docs.google.com/forms/
  2. Click the plus button to start a new form
  3. Give your form a title and description
  4. Add questions using the toolbar on the right
  5. Customize the form‘s look in the Theme menu
  6. Click the Send button to share your form via link, email, or embed code

Responses will automatically populate a Google Sheets spreadsheet that you can view and analyze. For basic data collection, Google Forms can be a great alternative to hand-coding HTML forms.

Real-World Form Examples
To solidify your understanding, let‘s look at a few examples of HTML forms in action on real websites.

[Example 1: A login form on GitHub] This form features:

  • Text inputs for username and password
  • Labels associated with each input
  • A submit button with custom styling
  • Positioning and sizing with CSS Grid
[Example 2: A checkout form on Amazon] This complex form includes:

  • Various input types (radio buttons for shipping, checkboxes for gift options, selects for quantities)
  • Inline validation to ensure valid shipping info
  • Conditional sections that appear based on previous selections
  • Styled buttons and layout with CSS
[Example 3: An embedded survey form on Typeform] Typeform is a service for creating online forms and surveys. This sample form shows:

  • Creative use of images and CSS animations
  • One question displayed at a time for better focus
  • Inputs with placeholders and floating labels
  • A progress bar showing overall completion

Hopefully these real-world examples give you a sense of what‘s possible with HTML forms when you combine all the concepts we‘ve covered.

Conclusion
HTML forms are a vital tool for collecting data from users on the web. By understanding the different parts that make up a form, how to submit form data, how to style forms with CSS, and how to enhance them with JavaScript, you‘ll be well-equipped to create functional and user-friendly forms for a variety of purposes.

To learn more, consult the additional resources below or try building some forms yourself. The best way to solidify your knowledge is through practice!

Additional Resources