Coding Wizard

Table of Contents

11. HTML Forms: Advanced Topics

Perhaps, HTML forms are amongst the most basic entities that happen in web applications. They meet the requirements of gathering input from the user and further interaction with backend systems. Part of the earlier chapters contains basics on form elements, control mechanisms, and submission techniques.But modern web applications create a lot of demand for advanced forms that demands advanced form techniques. In this chapter, we will explore topics that are much more advanced but can complement your HTML forms with better usability, accessibility, and functionality.


11.1 File Uploads

One of the more frequent use cases of web applications is the ability for end-users to upload documents, images, or other media files. The <input type=”file”> HTML element is used to create a file input field that allows end-users to select one or more files from their local device.

Basic Example:
<form action="/upload" method="post" enctype="multipart/form-data">
  <label for="fileUpload">Upload a file:</label>
  <input type="file" id="fileUpload" name="file">
  <button type="submit">Submit</button>
</form>

Explanation of the above example:

  • The <enctype=”multipart/form-data”> attribute is important while uploading files, because the <enctype=”multipart/form-data”> will take care of encoding the data properly for file uploads.
  • <input type=”file”> allows the user to browse from the local device
Multiple File Uploads:

You can also allow the upload of several files at a time by adding multiple to the input element.

<input type="file" id="fileUpload" name="files[]" multiple>
Limiting Acceptable File Types:

With accept you can limit what types of files to upload, say, images or documents.

<input type="file" id="fileUpload" name="file" accept=".jpg, .jpeg, .png">
JavaScript and File Previews:

By using JavaScript, you could make file uploads more friendly by offering to preview the selected file before submitting. Use this for images, especially.

<input type="file" id="fileUpload" accept="image/*">
<img id="preview" src="" alt="Image Preview" style="display:none;">

<script>
  const fileInput = document.getElementById('fileUpload');
  const preview = document.getElementById('preview');

  fileInput.addEventListener('change', function() {
    const file = this.files[0];
    if (file) {
      const reader = new FileReader();
      reader.onload = function(e) {
        preview.src = e.target.result;
        preview.style.display = 'block';
      }
      reader.readAsDataURL(file);
    }
  });
</script>

In this version, when the user selects an image file, FileReader is used to read the file, and a preview of the image is rendered in the document.


Interactive Activity 1: File Upload Feature

Goal: Create a simple form with a file upload input where users can select an image to upload to the server and will preview it before submitting their form.

Instructions:

  • Use the element to allow the user to select an image from their device.
  • Use JavaScript to display a preview of the selected image below the form before submission.
  • The form should have a submit button and minimal validation, for example, of the file type; for example, only images should be accepted, for .jpg, .png, etc.

Output:

  • Users can upload an image, preview of the image will automatically display on the page.

11.2 Date and Time Input Controls

HTML5 introduced some new form input types to help in picking dates and times. In this way, users can be given an option to input this information without manually inputting any value. The types available to select date and time values are date, time, datetime-local, month, and week.

Date Input:

The <input type=”date”> lets users select the day from a date picker.

<form>
  <label for="birthday">Choose your birth date:</label>
  <input type="date" id="birthday" name="birthday">
</form>
Time Input:

The <input type="time"> allows users to choose the time from a time picker.

<form>
  <label for="time">Choose a time:</label>
  <input type="time" id="time" name="time">
</form>
Datetime-Local Input:

The <input type="datetime-local"> merges the date input together with the time in one control.

<form>
  <label for="appointment">Schedule an appointment:</label>
  <input type="datetime-local" id="appointment" name="appointment">
</form>
Month and Week Inputs:

These are input types that enable the user to choose a month or a week from a calendar.

<!-- Month input -->
<label for="month">Select a month:</label>
<input type="month" id="month" name="month">

<!-- Week input -->
<label for="week">Select a week:</label>
<input type="week" id="week" name="week">
Setting Min and Max to Customize Date and Time Inputs:

To specify a date or time range, you use the min and max attributes. For example, to limit the date input to a certain range:

<input type="date" id="event" name="event" min="2024-01-01" max="2024-12-31">

Interactivity 2: Date and Time Input Form

Exercise: Code an appointment schedule form using HTML5 date and time input types.

Instructions:

  • Insert a date picker that enables the user to enter an appointment date.
  • Insert a time picker that allows the user to select the time for an appointment.
  • Ensure that the date selected cannot be in the past and the time cannot fall on business day shift hours, which would be for instance between 9 AM and 5 PM.

Expected Result:

  • The form should reject the submission of invalid dates and times and only allow valid dates and times.
  • Implement minimal validation on dates and times against validity.

11.3 Form Fieldsets and Legends

You can group a large number of form controls, or even elements containing form controls for a more complex form with many sections, by employing <fieldset> and <legend> to group related form controls, thus improving both the structure of the form and its accessibility.

Fieldset and Legend Example:
<form>
  <fieldset>
    <legend>Personal Information</legend>
    <label for="name">Name:</label>
    <input type="text" id="name" name="name">

    <label for="email">Email:</label>
    <input type="email" id="email" name="email">
  </fieldset>

  <fieldset>
    <legend>Payment Details</legend>
    <label for="card">Card Number:</label>
    <input type="text" id="card" name="card">

    <label for="expiry">Expiry Date:</label>
    <input type="month" id="expiry" name="expiry">
  </fieldset>

  <button type="submit">Submit</button>
</form>

The <fieldset> groups related inputs, and the <legend> supplies a heading to the fieldset, making it easier to understand. This is also very useful for accessibility because screen readers will declare the group name (<legend>) before reading the input labels.

Styling Fieldsets:

By default, fieldsets have a border around them, but you can style that as well with CSS:

fieldset {
  border: 2px solid #4CAF50;
  padding: 10px;
}

legend {
  font-weight: bold;
}

Interactive Activity 3: Grouping Form Controls Using Fieldsets

Objective: Create a multi-page form consisting of two sections. This is section one which contains personal details and section two, which comprises of payment details, on using fieldset and legends.

Instruction:

  • Group the related form controls into two sections namely Personal Information and Payment Details.
  • Use element to combine controls together, and to furnish the title of each section.
  • The following structure should be composed in the form:
  1. Personal Information
  2. Name
  3. Email
  4. Payment Details
  5. Credit Card Number
  6. Expiry Date
  • Organize the form in an orderly fashion, that is, into logical sections with clear labels.

11.4 Form Validation with JavaScript

Client-side validation means form data is valid before it’s sent to the server. HTML5 does have some basic validation with attributes like required, minlength, and maxlength, but JavaScript allows you to do more-complex validation scenarios.

Basic HTML5 Validation:
<form>
  <label for="email">Email:</label>
  <input type="email" id="email" name="email" required>

  <button type="submit">Submit</button>
</form>

The required attribute ensures that a user is not allowed to submit the form without filling the email field. The email type ensures that the value entered is in a valid email format.

JavaScript Custom Validation Example:

You might use JavaScript’s addEventListener to validate form input values before submission for more complex validation.

<form id="myForm">
  <label for="username">Username (at least 5 characters):</label>
  <input type="text" id="username" name="username">

  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById('myForm').addEventListener('submit', function(e) {
    const username = document.getElementById('username').value;
    if (username.length < 5) {
      e.preventDefault();
      alert('Username must be at least 5 characters long.');
    }
  });
</script>

Prevent the form from submitting by attaching an event handler (e.preventDefault()), if the username input contains fewer than 5 characters. That way, the bad data will not be sent to the server.

Displaying Errors:

Instead of having inline errors it is much better for usability:

<form id="myForm">
  <label for="username">Username:</label>
  <input type="text" id="username" name="username">
  <span id="error" style="color:red;"></span>

  <button type="submit">Submit</button>
</form>

<script>
  document.getElementById('myForm').addEventListener('submit', function(e) {
    const username = document.getElementById('username').value;
    const error = document.getElementById('error');
    if (username.length < 5) {
      e.preventDefault();
      error.textContent = 'Username must be at least 5 characters long.';
    } else {
      error.textContent = '';
    }
  });
</script>

Interactive Activity 4: Custom Form Validation with JavaScript

Objective: Create a sign-up form with custom JavaScript validation.

  1. Instructions:
    • Build a simple form with fields for username, email, and password.
    • Use JavaScript to validate the form:
      • The username must be at least 5 characters.
      • The email must follow a proper email format.
      • The password must contain at least 8 characters, including one number and one special character.
    • Display error messages next to the input fields if the validation fails.
  2. Expected Output:
    • The form prevents submission until all fields are valid.
    • Error messages appear in red when inputs are invalid.

11.5 Form Accessibility and ARIA Roles

Accessibility should be a priority to make your web forms accessible for people with disabilities, especially those who rely on assistive technologies like screen readers. ARIA is a set of attributes that assists in accessibility.

Application of Labels in Accessibility:

The <label> element should always be linked with form controls to achieve accessibility. It automatically focuses its paired input field when you click on its label.

<label for="username">Username:</label>
<input type="text" id="username" name="username">

In this example, the for attribute of the <label> references it to the id of the input element. This is important because screen readers will say the label once the input receives focus.

ARIA Attributes:

ARIA roles and attributes extend form accessibility even further. For example, aria-required=”true” can display that a field must be filled in, even if the required attribute is not being used.

<label for="name">Name (Required):</label>
<input type="text" id="name" aria-required="true">
Using Fieldsets and Legends for Accessibility:

As mentioned earlier, fieldsets and legends group form controls logically, making forms easier to navigate for users with screen readers. For even more clarity, ARIA roles like role=”group” can be used to explicitly define related elements.


Interactive Activity 5: Accessible Form with ARIA Roles

Objective: Improve the accessibility of a form using ARIA roles and attributes.

  1. Instructions:
    • Create a basic form that includes text inputs for name and email, a date picker for birthdate, and a file upload option.
    • Add ARIA attributes to improve accessibility, such as aria-required="true" for required fields.
    • Add labels for each input element using the <label> element.
    • Group the fields logically with <fieldset> and <legend> elements to further enhance accessibility.
  2. Expected Output:
    • Users can navigate the form easily with a screen reader, and ARIA attributes will provide additional context.

Quizz Time:

Form Elements Quiz
1. Which attribute is necessary when uploading files in a form?
2. What is the purpose of the <fieldset> and <legend> elements in a form?
3. Which of the following attributes limits the acceptable file types for a file input?
4. In which scenario should you use JavaScript for form validation?
5. Which ARIA attribute indicates that a form field is required?
6. Which input type would you use to allow users to select both a date and a time?
7. What does the multiple attribute do in a file input field?

Conclusion

With mastery of these advanced form topics you can build incredibly interactive, user-friendly, and accessible forms that measurably improve the user experience and functionality. You are expanding your HTML toolbox with the addition of file uploads, date/time inputs, fieldsets, custom validation, and accessibility techniques. Finally, adding ARIA roles to your forms makes them available to all, regardless of ability.