How to Create a Form with Multiple Steps using CSS and JavaScript ?

A multi-step form divides a long form into smaller, more manageable sections or steps. This makes it easier for users to fill out and makes the form less intimidating. We will explore the approach to building a multi-step form using CSS and JavaScript.

Approach

  • Create a form container. Inside the form create multiple <div> elements for adding different steps to the form.
  • Add related input fields in each step. Create a container for buttons that hold buttons for navigation between steps like next, previous, and submit.
  • Initially hide all steps except the active one. Add JavaScript for interactivity to the form.
  • Create an updateButtons() function which will determine which buttons to display. It will adjust the visibility of the “Previous”, “Next” and “Submit” buttons based on the current step.
  • Add Event listeners to the “Next” and “Previous” buttons to handle navigation between steps.
  • Create the validateForm() function which checks if the inputs in the current step are valid.

Example: This example shows how to create a multi-step form using CSS and JavaScript.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0">
    <title>Multi-Step Form</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            display: flex;
            justify-content: center;
            align-items: center;
            height: 100vh;
            background-color: #f5f5f5;
            margin: 0;
        }

        form {
            width: 100%;
            max-width: 500px;
            background: white;
            padding: 20px;
            border-radius: 5px;
            box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
        }

        .step {
            display: none;
        }

        .step.active {
            display: block;
        }

        h2 {
            margin-top: 0;
        }

        label {
            display: block;
            margin: 10px 0 5px;
        }

        input,
        textarea {
            width: 98%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ccc;
            border-radius: 5px;
        }

        .button-container {
            overflow: auto;
            margin-top: 20px;
            text-align: right;
        }

        .button-container button {
            padding: 10px 20px;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            margin-left: 10px;
        }

        button.prev {
            background-color: #f1f1f1;
            float: left;
            margin-left: 62%;
        }

        button.next {
            background-color: #4CAF50;
            color: white;
            float: right;
        }

        button[type="submit"] {
            background-color: #4CAF50;
            color: white;
            float: right;
        }
    </style>
</head>

<body>
    <form id="multiStepForm">
        <div class="step active">
            <h2>Step 1: Name</h2>
            <label for="firstName">
              First Name:
              </label>
            <input type="text" id="firstName" 
                   name="firstName">
            <label for="lastName">
              Last Name:
              </label>
            <input type="text" id="lastName" 
                   name="lastName">
        </div>
        <div class="step">
            <h2>Step 2: Contact details</h2>
            <label for="text">Email:</label>
            <input type="email" id="email" 
                   name="email">
            <label for="contactNumber">
              Contact Number:
              </label>
            <input type="tel" id="contactNumber" 
                   name="contactNumber">
        </div>
        <div class="step">
            <h2>Step 3: Address detail</h2>
            <label for="address">Address:</label>
            <textarea id="address" name="address" 
                      rows="6" 
                      placeholder="Detailed Address" 
                      required>
              </textarea>
        </div>
        <div class="button-container">
            <button type="button" 
                    class="prev">
              Previous
              </button>
            <button type="button" 
                    class="next">
              Next
              </button>
            <button type="submit" 
                    style="display: none;">
              Submit
              </button>
        </div>
    </form>

    <script>
        document.addEventListener('DOMContentLoaded', function () {
            const form = document.getElementById('multiStepForm');
            const steps = form.querySelectorAll('.step');
            const prevButton = form.querySelector('.prev');
            const nextButton = form.querySelector('.next');
            let currentStep = 0;

            updateButtons();

            nextButton.addEventListener('click', () => {
                if (validateForm()) {
                    steps[currentStep].classList
                                        .remove('active');
                    currentStep++;
                    steps[currentStep].classList
                                        .add('active');
                    updateButtons();
                }
            });

            prevButton.addEventListener('click', () => {
                steps[currentStep].classList
                                    .remove('active');
                currentStep--;
                steps[currentStep].classList
                                    .add('active');
                updateButtons();
            });

            form.addEventListener('submit', (event) => {
                if (!validateForm()) {
                    event.preventDefault();
                }
            });

            function validateForm() {
                const currentInputs = steps[currentStep]
                    .querySelectorAll('input, textarea');
                let valid = true;
                currentInputs.forEach(input => {
                    if (!input.checkValidity()) {
                        input.reportValidity();
                        valid = false;
                    }
                });
                return valid;
            }

            function updateButtons() {
                if (currentStep === 0) {
                    prevButton.style.display = 'none';
                } else {
                    prevButton.style.display = 'inline-block';
                }

                if (currentStep === steps.length - 1) {
                    nextButton.style.display = 'none';
                    form.querySelector('button[type="submit"]')
                          .style.display = 'inline-block';
                } else {
                    nextButton.style.display = 'inline-block';
                    form.querySelector('button[type="submit"]')
                          .style.display = 'none';
                }
            }
        });
    </script>
</body>

</html>

Output:

Output