Menu

HTML & JS Topic

HTML Forms – Basics

What Are HTML Forms?

Forms collect user input and send it to a server for processing. They're essential for:

  • Login/registration

  • Contact forms

  • Search boxes

  • Surveys and polls

  • E-commerce checkout

Basic Form Structure

html

<form action="/submit" method="POST">
  <!-- Form elements go here -->
</form>

Key Form Attributes:

  • action: URL where form data is sent

  • method: HTTP method (GET or POST)

  • enctype: Encoding type for file uploads

  • target: Where to display response

  • autocomplete: Enable/disable autocomplete

Input Types (The Most Important Ones)

Text Inputs

html

<!-- Basic text -->
<input type="text" name="username" placeholder="Enter username">

<!-- Password (hidden characters) -->
<input type="password" name="password">

<!-- Email with validation -->
<input type="email" name="email">

<!-- Number input -->
<input type="number" name="age" min="0" max="120">

<!-- Telephone -->
<input type="tel" name="phone">

<!-- URL -->
<input type="url" name="website">

<!-- Search box -->
<input type="search" name="query">

Selection Inputs

html

<!-- Checkbox (multiple selections) -->
<input type="checkbox" name="interests" value="sports"> Sports
<input type="checkbox" name="interests" value="music"> Music

<!-- Radio buttons (single selection) -->
<input type="radio" name="gender" value="male"> Male
<input type="radio" name="gender" value="female"> Female

<!-- Dropdown select -->
<select name="country">
  <option value="">Select country</option>
  <option value="us">United States</option>
  <option value="uk">United Kingdom</option>
</select>

<!-- Multi-select -->
<select name="colors" multiple>
  <option value="red">Red</option>
  <option value="green">Green</option>
</select>

Specialized Inputs

html

<!-- File upload -->
<input type="file" name="document">

<!-- Date picker -->
<input type="date" name="birthday">

<!-- Color picker -->
<input type="color" name="favcolor">

<!-- Range slider -->
<input type="range" name="volume" min="0" max="100">

<!-- Hidden field -->
<input type="hidden" name="user_id" value="123">

Labels – Connecting Text to Inputs

Proper Label Usage

Always associate labels with inputs for accessibility:

html

<!-- Method 1: Wrap input in label -->
<label>
  Username:
  <input type="text" name="username">
</label>

<!-- Method 2: Use 'for' attribute (recommended) -->
<label for="email">Email address:</label>
<input type="email" id="email" name="email">

<!-- Method 3: For checkboxes/radios -->
<label for="subscribe">
  <input type="checkbox" id="subscribe" name="subscribe">
  Subscribe to newsletter
</label>

Benefits:

  • Screen readers can announce the label

  • Users can click the label to focus the input

  • Better touch targets on mobile

Buttons in Forms

Button Types

html

<!-- Submit button (sends form data) -->
<button type="submit">Submit Form</button>
<input type="submit" value="Submit">

<!-- Reset button (clears form) -->
<button type="reset">Clear Form</button>
<input type="reset" value="Reset">

<!-- Regular button (needs JavaScript) -->
<button type="button">Click Me</button>
<input type="button" value="Click">

<!-- Button with image -->
<input type="image" src="submit.png" alt="Submit">

Button Best Practices

html

<!-- Accessible buttons -->
<button type="submit" aria-label="Submit contact form">
  Submit
</button>

<!-- Disabled state -->
<button type="submit" disabled>
  Processing...
</button>

<!-- Styled buttons -->
<button type="submit" class="btn btn-primary">
  <i class="icon-send"></i> Send Message
</button>

Form Submission Basics

GET vs POST Methods

html

<!-- GET - Data in URL (for searches) -->
<form action="/search" method="GET">
  <input type="text" name="q" placeholder="Search...">
  <button type="submit">Search</button>
</form>
<!-- Result: /search?q=user+query -->

<!-- POST - Data in request body (for sensitive data) -->
<form action="/login" method="POST">
  <input type="text" name="username">
  <input type="password" name="password">
  <button type="submit">Login</button>
</form>

When to use each:

  • GET: Bookmarkable URLs, sharing links, searches (data visible in URL)

  • POST: Login, registration, payments (data hidden, more secure)

Form Validation Attributes

html

<form action="/submit" method="POST">
  <!-- Required field -->
  <input type="text" name="name" required>
  
  <!-- Minimum length -->
  <input type="text" name="username" minlength="3">
  
  <!-- Maximum length -->
  <input type="text" name="title" maxlength="50">
  
  <!-- Pattern matching (regex) -->
  <input type="text" name="zipcode" pattern="[0-9]{5}">
  
  <!-- Placeholder text -->
  <input type="email" placeholder="email@example.com">
  
  <!-- Disabled field -->
  <input type="text" name="readonly" value="Can't edit" disabled>
  
  <!-- Read-only field -->
  <input type="text" name="display" value="Display only" readonly>
</form>

Complete Form Example

html

<!DOCTYPE html>
<html>
<head>
    <title>Registration Form</title>
    <style>
        form { max-width: 500px; margin: 20px auto; padding: 20px; border: 1px solid #ddd; }
        .form-group { margin-bottom: 15px; }
        label { display: block; margin-bottom: 5px; font-weight: bold; }
        input, select, textarea { width: 100%; padding: 8px; box-sizing: border-box; }
        button { background: #007bff; color: white; border: none; padding: 10px 20px; }
        button:hover { background: #0056b3; }
        .error { color: red; font-size: 0.9em; }
    </style>
</head>
<body>
    <h1>User Registration</h1>
    
    <form action="/register" method="POST" novalidate>
        
        <!-- Text Input with Label -->
        <div class="form-group">
            <label for="fullname">Full Name *</label>
            <input type="text" id="fullname" name="fullname" 
                   required minlength="2" 
                   placeholder="Enter your full name">
            <div class="error" id="name-error"></div>
        </div>
        
        <!-- Email Input -->
        <div class="form-group">
            <label for="email">Email Address *</label>
            <input type="email" id="email" name="email" 
                   required 
                   placeholder="you@example.com">
        </div>
        
        <!-- Password -->
        <div class="form-group">
            <label for="password">Password *</label>
            <input type="password" id="password" name="password" 
                   required minlength="8"
                   placeholder="Minimum 8 characters">
        </div>
        
        <!-- Date of Birth -->
        <div class="form-group">
            <label for="dob">Date of Birth</label>
            <input type="date" id="dob" name="dob">
        </div>
        
        <!-- Radio Buttons -->
        <div class="form-group">
            <label>Gender</label>
            <label>
                <input type="radio" name="gender" value="male"> Male
            </label>
            <label>
                <input type="radio" name="gender" value="female"> Female
            </label>
            <label>
                <input type="radio" name="gender" value="other"> Other
            </label>
        </div>
        
        <!-- Checkboxes -->
        <div class="form-group">
            <label>Interests</label>
            <label>
                <input type="checkbox" name="interests" value="tech"> Technology
            </label>
            <label>
                <input type="checkbox" name="interests" value="sports"> Sports
            </label>
            <label>
                <input type="checkbox" name="interests" value="music"> Music
            </label>
        </div>
        
        <!-- Dropdown Select -->
        <div class="form-group">
            <label for="country">Country</label>
            <select id="country" name="country">
                <option value="">Select a country</option>
                <option value="us">United States</option>
                <option value="uk">United Kingdom</option>
                <option value="ca">Canada</option>
            </select>
        </div>
        
        <!-- Textarea -->
        <div class="form-group">
            <label for="bio">Biography</label>
            <textarea id="bio" name="bio" rows="4" 
                      placeholder="Tell us about yourself..."></textarea>
        </div>
        
        <!-- File Upload -->
        <div class="form-group">
            <label for="avatar">Profile Picture</label>
            <input type="file" id="avatar" name="avatar" accept="image/*">
        </div>
        
        <!-- Terms Agreement -->
        <div class="form-group">
            <label>
                <input type="checkbox" name="terms" required>
                I agree to the Terms and Conditions
            </label>
        </div>
        
        <!-- Submit & Reset Buttons -->
        <div class="form-group">
            <button type="submit">Create Account</button>
            <button type="reset">Clear Form</button>
        </div>
        
        <!-- Hidden Field -->
        <input type="hidden" name="referrer" value="website">
        
    </form>
    
    <script>
        // Basic form validation
        document.querySelector('form').addEventListener('submit', function(e) {
            const nameInput = document.getElementById('fullname');
            const errorDiv = document.getElementById('name-error');
            
            if (nameInput.value.trim().length < 2) {
                e.preventDefault();
                errorDiv.textContent = 'Name must be at least 2 characters';
                nameInput.focus();
            } else {
                errorDiv.textContent = '';
            }
        });
    </script>
</body>
</html>

Key Best Practices

  1. Always use <label> elements – Required for accessibility

  2. Group related fields with <fieldset> and <legend>

  3. Use proper input types for better mobile UX

  4. Client-side validation improves user experience

  5. Server-side validation is mandatory for security

  6. Use required attribute for essential fields

  7. Provide clear error messages

  8. Consider mobile users with appropriate input types

Common Form Patterns

html

<!-- Login Form -->
<form action="/login" method="POST">
    <input type="text" name="username" placeholder="Username" required>
    <input type="password" name="password" placeholder="Password" required>
    <label><input type="checkbox" name="remember"> Remember me</label>
    <button type="submit">Sign In</button>
</form>

<!-- Search Form -->
<form action="/search" method="GET" role="search">
    <input type="search" name="q" placeholder="Search...">
    <button type="submit">🔍</button>
</form>

<!-- Contact Form -->
<form action="/contact" method="POST">
    <input type="text" name="name" placeholder="Your Name" required>
    <input type="email" name="email" placeholder="Your Email" required>
    <textarea name="message" placeholder="Your Message" required></textarea>
    <button type="submit">Send Message</button>
</form>

Forms are the primary way users interact with web applications. Properly structured forms with clear labels, appropriate input types, and good validation create better user experiences and more accessible websites.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?