Blog>
Snippets

Multi-Step Form with Progress Bar

Implement a multi-step form that saves the state of each step, with a progress bar showing completion status, providing next and back buttons to navigate between form sections.
let currentStep = 0;

function showCurrentStep() {
  const steps = document.querySelectorAll('.step');
  const progressBar = document.querySelector('#progress-bar');
  steps.forEach((step, index) => {
    step.style.display = index === currentStep ? 'block' : 'none';
  });
  progressBar.value = ((currentStep + 1) / steps.length) * 100;
}

function nextStep() {
  const steps = document.querySelectorAll('.step');
  if (currentStep < steps.length - 1) {
    currentStep++;
    showCurrentStep();
  }
}

function prevStep() {
  if (currentStep > 0) {
    currentStep--;
    showCurrentStep();
  }
}

// Initialization
document.addEventListener('DOMContentLoaded', showCurrentStep);
document.querySelector('#next').addEventListener('click', nextStep);
document.querySelector('#back').addEventListener('click', prevStep);
This code manages the multi-step form navigation and progress bar update. It initializes the form by showing the first step, binds next and back button click events, and updates the progress bar as the user navigates.
document.addEventListener('DOMContentLoaded', function() {
  let data = {};

  document.querySelector('form').addEventListener('submit', function(event) {
    event.preventDefault();
    const inputs = this.querySelectorAll('input, select, textarea');
    inputs.forEach(input => {
      data[input.name] = input.value;
    });
  });
});
This code retrieves the data from inputs when the form is submitted and prevents the form's default submission behavior to handle the data manually. It stores the input values into an object.
function saveStepData() {
  const currentInputs = document.querySelectorAll('.step')[currentStep].querySelectorAll('input, select, textarea');
  currentInputs.forEach(input => {
    localStorage.setItem(input.name, input.value);
  });
}

function loadStepData() {
  const currentInputs = document.querySelectorAll('.step')[currentStep].querySelectorAll('input, select, textarea');
  currentInputs.forEach(input => {
    input.value = localStorage.getItem(input.name) || '';
  });
}
This code saves the current step data to local storage and loads it when a user revisits a step. It ensures that the user's progress is not lost if they navigate back and forth between the form steps.