JavaScript
Intermediate
Updated 5h ago
Multi-Step Form with Progress Bar
A multi-step form with visual progress bar, next/previous navigation, and per-step validation.
<div id="multiStepForm">
<div class="progress-bar" style="height:4px;background:#e5e7eb;border-radius:2px;margin-bottom:20px">
<div id="progress" style="height:100%;width:33%;background:#6366f1;border-radius:2px;transition:width 0.3s"></div>
</div>
<div class="step" data-step="1">
<h3>Step 1: Personal Info</h3>
<input type="text" name="name" placeholder="Full Name" required>
<input type="email" name="email" placeholder="Email" required>
</div>
<div class="step" data-step="2" style="display:none">
<h3>Step 2: Details</h3>
<input type="tel" name="phone" placeholder="Phone" required>
<select name="plan"><option value="basic">Basic</option><option value="pro">Pro</option></select>
</div>
<div class="step" data-step="3" style="display:none">
<h3>Step 3: Confirm</h3>
<p>Review your information and submit.</p>
</div>
<button type="button" id="prevBtn" onclick="navigate(-1)" style="display:none">Previous</button>
<button type="button" id="nextBtn" onclick="navigate(1)">Next</button>
</div>
<script>
let currentStep = 1;
const totalSteps = 3;
function navigate(dir) {
const next = currentStep + dir;
if (next < 1 || next > totalSteps) return;
if (dir === 1) {
const inputs = document.querySelector(`.step[data-step="${currentStep}"]`).querySelectorAll("input[required]");
for (const input of inputs) { if (!input.value.trim()) { input.focus(); return; } }
}
document.querySelector(`.step[data-step="${currentStep}"]`).style.display = "none";
currentStep = next;
document.querySelector(`.step[data-step="${currentStep}"]`).style.display = "block";
document.getElementById("progress").style.width = (currentStep / totalSteps * 100) + "%";
document.getElementById("prevBtn").style.display = currentStep > 1 ? "inline" : "none";
const nextBtn = document.getElementById("nextBtn");
nextBtn.textContent = currentStep === totalSteps ? "Submit" : "Next";
if (currentStep === totalSteps) { nextBtn.setAttribute("type", "submit"); }
}
</script>
Technical Breakdown
Multi-step form with progress bar, per-step validation, and navigation buttons.
Pitfalls & Solutions
1. Not validating per step. 2. Progress bar not updating. 3. Submit button type not changing.
Common Questions
Can I add more steps?
Yes, add more div.step elements with data-step attributes and update the totalSteps variable.
Tags
#JavaScript
#Forms