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:
- The
- 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
- 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
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
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
- 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:
The key accessibility features include:
- Using
- 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:
- Gets references to the email input and error message span
- Listens for changes to the email input value
- Checks if the entered email is valid using the input‘s built-in validity property
- 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:
- Go to https://docs.google.com/forms/
- Click the plus button to start a new form
- Give your form a title and description
- Add questions using the toolbar on the right
- Customize the form‘s look in the Theme menu
- 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.
- Text inputs for username and password
- Labels associated with each input
- A submit button with custom styling
- Positioning and sizing with CSS Grid
- 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
- 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
- MDN Web Docs: HTML forms guide – https://developer.mozilla.org/en-US/docs/Learn/Forms
- web.dev: Best practices for form design – https://web.dev/learn/forms/
- W3Schools: HTML Form Elements – https://www.w3schools.com/html/html_form_elements.asp
- Google Forms – https://www.google.com/forms/about/