Skip to content

Vanilla JS/HTML Forms Tutorial

Learning Objects

  • Identify the HTML elements used to build forms
  • Know how to build a basic form
  • Know how to use preventDefault to implement a custom handler in JavaScript

Introduction

In this lesson we'll cover the basics of creating and integrating HTML forms with Vanilla JavaScript. We'll start with simple concepts and gradually build a basic form with JavaScript integration.

HTML Form Basics

Creating a Basic Form

HTML forms are used to collect user input. A basic form can be created using the <form> element.

<form>
  <!-- Form elements will go here -->
</form>

Form Elements

Common elements used in a form include: - <input>: for user input. - <label>: to label an input. - <button>: to submit the form.

Example:

<form>
  <label for="name">Name:</label>
  <input type="text" id="name" name="name">
  <button type="submit">Submit</button>
</form>

Input Types

The <input> element in HTML can take various values for its "type" attribute, each designed for a specific kind of data input. Here's an overview of the most common types:

Text

  • type="text": The default type for simple text input.
  • Use Case: To enter names, usernames, or any other textual information.
  • Example: <input type="text" name="username">

Password

  • type="password": For input fields where the characters entered should be obscured.
  • Use Case: For entering passwords or other sensitive data.
  • Example: <input type="password" name="password">

Email

  • type="email": For email addresses, includes basic validation for email format.
  • Use Case: For entering email addresses.
  • Example: <input type="email" name="email">

Number

  • type="number": For numerical input, can include min, max, and step attributes.
  • Use Case: For entering numbers like age, price, or quantity.
  • Example: <input type="number" name="quantity" min="1">

Date

  • type="date": For selecting dates from a calendar picker.
  • Use Case: For entering dates like birthdays, appointments, etc.
  • Example: <input type="date" name="birthday">

Time

  • type="time": For selecting a time.
  • Use Case: For entering time values like alarm settings, schedule, etc.
  • Example: <input type="time" name="alarm">

Checkbox

  • type="checkbox": For options that can be selected independently.
  • Use Case: For multiple choices where more than one option can be selected, like in surveys or settings.
  • Example: <input type="checkbox" name="subscribe" value="newsletter"> Subscribe to newsletter

Radio

  • type="radio": For mutually exclusive choices.
  • Use Case: For a set of options where only one choice is allowed, like in polls or forms.
  • Example:
    <input type="radio" name="gender" value="male" id="male">
    <label for="male">Male</label><br>
    <input type="radio" name="gender" value="female" id="female">
    <label for="female">Female</label>
    

File

  • type="file": For file upload.
  • Use Case: For uploading files like images, documents, etc.
  • Example: <input type="file" name="resume">

Submit

  • type="submit": A button to submit the form.
  • Use Case: To submit the form data to a server.
  • Example: <input type="submit" value="Submit">

Reset

  • type="reset": A button to reset the form fields to their initial values.
  • Use Case: To clear the form inputs.
  • Example: <input type="reset" value="Reset">

Range

  • type="range": For inputting a value from a range.
  • Use Case: For settings that require a value within a range, like volume control.
  • Example: <input type="range" name="volume" min="0" max="100">

Color

  • type="color": For color selection.
  • Use Case: For choosing a color from a color picker.
  • Example: <input type="color" name="favColor">

Each type is designed to make the data entry experience more user-friendly and efficient, and to ensure that the data collected is in the format most suitable for its intended use.

JavaScript Integration

Accessing Form Elements

You can access form elements in JavaScript using the document object.

document.getElementById('name');

Handling Form Submission

To handle form submission, add an event listener to the form.

const form = document.querySelector('form');

form.addEventListener('submit', function(event) {
  event.preventDefault(); // Prevents the default form submission behavior
  // Form handling logic goes here
});

Basic Validation

You can perform basic validation before submitting the form.

form.addEventListener('submit', function(event) {
  event.preventDefault();
  const name = document.getElementById('name').value;
  if (name.length < 3) {
    alert('Name must be at least 3 characters long.');
    return;
  }
  // Proceed with form submission
});

Complete Example

Here is a complete example of an HTML form with Vanilla JavaScript integration.

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Basic Form</title>
</head>
<body>
    <form id="myForm">
        <label for="name">Name:</label>
        <input type="text" id="name" name="name">
        <button type="submit">Submit</button>
    </form>

    <script src="script.js"></script>
</body>
</html>

JavaScript (script.js)

document.addEventListener('DOMContentLoaded', function() {
  const form = document.getElementById('myForm');

  form.addEventListener('submit', function(event) {
    event.preventDefault();
    const name = document.getElementById('name').value;
    if (name.length < 3) {
      alert('Name must be at least 3 characters long.');
      return;
    }
    // Additional processing
    alert('Form submitted!');
  });
});

Conclusion

This lesson provided a basic introduction to creating and using HTML forms with Vanilla JavaScript. To solidify your learning, experiment with different form elements and JavaScript methods to enhance your forms.