A High-Level Overview
HTML forms allow collecting user input through fields, dropdowns, buttons and other elements within a <form>
tag. They are sent to a server for processing via JavaScript or web languages like PHP.
This guide will break down:
- HTML form anatomy with code examples
- Building common scenarios like contact forms
- Validation and security best practices
- Submitting data to databases
- Styling aesthetically pleasing forms
- Alternative form builders
With foundational knowledge of HTML forms, you can level up your web development skills!
A Brief History of Forms
HTML forms have been central to web interactivity since the beginning. Let‘s walk through some key developments:
HTML 2 (1995) – First form inputs like text fields, radio buttons
HTML 3.2 (1997) – Email/URL input types, form data validation attributes added
HTML 4 (1997) – Date pickers, color picker, calendar, slider inputs introduced
HTML 5 (2014) – Existing types expanded (email, number, url), new mobile-friendly inputs (search, range)
Here is a snippet showing HTML5 additions:
<!-- Numeric input -->
<input type="number">
<!-- Slider input -->
<input type="range">
<!-- Search input -->
<input type="search">
The history shows a progression towards richer form functionality over 25+ years!
Anatomy of an HTML Form
The key ingredients of an HTML form include:
The <form>
Element
The <form>
tag wraps all fields and controls:
<form action="/form-handler" method="post">
<!-- Form elements here -->
</form>
Form Control Elements
Inputs within the form for user entries:
<!-- Text input -->
<input type="text">
<!-- Email input -->
<input type="email">
<!-- Number input -->
<input type="number">
<!-- Dropdown select -->
<select>
<option>Option 1</option>
</select>
<!-- Multi-line text -->
<textarea></textarea>
<!-- Submit button -->
<button type="submit">Submit</button>
The <label>
Element
Labels elements to identify form controls:
<label for="name">Name:</label>
<input type="text" id="name">
These are the building blocks. Now let‘s see them in action!
HTML Form Example 1: Contact Form
A common use case is a contact form for site visitors to get in touch:
And the HTML:
<form action="contact.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br>
<label for="email">Email:</label><br>
<input type="email" id="email" name="email"><br>
<label for="message">Message:</label><br>
<textarea id="message" name="message"></textarea><br>
<button type="submit">Send Message</button>
</form>
The PHP script (contact.php
) can process submitted data:
$name = $_POST[‘name‘];
$email = $_POST[‘email‘];
$message = $_POST[‘message‘];
// Save to database, send email etc...
Next let‘s explore another scenario…
HTML Form Example 2: Survey
Surveys use a variety of form control elements. Here is an example multi-question survey:
The HTML markup:
<form action="collect.php" method="post">
<label for="name">Name:</label><br>
<input type="text" id="name" name="name"><br><br>
<label>Are you satisfied with our service?</label><br>
<input type="radio" name="satisfied" value="yes"> Yes
<input type="radio" name="satisfied" value="somewhat"> Somewhat
<input type="radio" name="satisfied" value="no"> No<br><br>
<label>What device(s) do you use to read our website? (Select all that apply)</label><br>
<input type="checkbox" name="devices[]" value="desktop"> Desktop
<input type="checkbox" name="devices[]" value="tablet"> Tablet
<input type="checkbox" name="devices[]" value="phone"> Phone<br><br>
<label>Additional comments:</label><br>
<textarea name="comments"></textarea><br>
<button type="submit">Submit Survey</button>
</form>
Key points:
- Radio buttons allow single choice selections
- Checkboxes use
name="devices[]"
to support multi-selections stored in array - The
<textarea>
field enables multiline text comments
This covers additional common form elements!
Validating and Sanitizing Form Data
We have working forms – but they need some best practices for security and validation:
Client-Side Validation
Validate via HTML5 attributes before sending data:
<!-- Required -->
<input type="text" required>
<!-- Max characters -->
<input type="text" maxlength="500">
<!-- Validate as email -->
<input type="email">
Server-Side Validation
Double check input on the server side before processing:
$email = $_POST[‘email‘];
// Additional PHP validation
if (filter_var($email, FILTER_VALIDATE_EMAIL) == false) {
echo "Invalid email";
exit;
}
This protects against attacks via fake requests.
Sanitization
Escapes or encodes data to prevent JavaScript injection etc:
$comments = $_POST[‘comments‘];
// Escape HTML tags
$comments = htmlspecialchars($comments);
Implement these measures consistently for professional, secure forms.
Submitting Form Data to a Database
Once validated/sanitized, save form entries into a database.
For example, this PHP code connects to MySQL and inserts the input:
// Connect to MySQL
$dbc = mysqli_connect(‘localhost‘,‘user‘,‘pass‘,‘db‘);
// Insert survey results
$query = "INSERT INTO survey_responses (name, satisfied, devices, comments)
VALUES (‘" . $_POST[‘name‘] . "‘,
‘" . $_POST[‘satisfied‘] . "‘,
‘" . implode(‘,‘, $_POST[‘devices‘]) . "‘,
‘" . $_POST[‘comments‘] . "‘)";
mysqli_query($dbc, $query);
The submitted data can now be stored and analyzed!
Styling Beautiful HTML Forms
Let‘s explore how styling can transform form aesthetics:
Some CSS techniques:
/* Center align */
form {
width: 300px;
margin: 0 auto;
}
/* Style labels */
label {
display: block;
padding-bottom: 5px;
}
/* Style inputs */
input,
textarea {
width: 100%;
padding: 8px;
border: 1px solid #ddd;
}
/* Button styles */
button {
padding: 10px 15px;
background: #2b85e4;
color: white;
}
Proper styling brings forms to life visually! Just don‘t forget functionality in pursuit of beauty.
Common Form Myths vs Facts
Let‘s dispel some need-to-know myths:
Myth: HTML forms can use any backend language
Fact: Server-side code is needed to process submissions from PHP, Python, C#, Ruby, Java, JavaScript etc
Myth: Forms always refresh the page on submit
Fact: With JavaScript, you can submit AJAX requests avoiding page reloads
Myth: Styling affects form functionality
Fact: Inputs maintain full functionality regardless of CSS styling tweaks
Form Basics FAQs
Some quick questions from beginners:
- What‘s the difference between POST vs GET requests?
- POST keeps data in request body while GET exposes it in the URL
- Should I validate forms before styling?
- Yes, functionality before aesthetics as broken forms won‘t convert
- Can forms connect to APIs instead of databases?
- Absolutely, you can POST JSON to REST APIs and process asynchronously
- Are forms bad for SEO rankings?
- No, semantic HTML forms follow standards and can improve keyword relevancy
Hope these help explain common points of confusion!
Key Takeaways
We covered a lot regarding HTML forms. To recap:
- They allow capturing a variety of user inputs with the
<form>
element - Common visual elements include text fields, buttons, checkboxes
- Validation and sanitization help improve security
- Backends like PHP can insert data into databases
- CSS handles presentation while HTML maintains functionality
- Alternatives exist but standard forms power many websites
With this knowledge, you can build featured-packed, interactive sites!
Have any other questions? Just ask!