Developing a multi-step form with validation that transmits data to various endpoints is attainable through vanilla JavaScript. Below is a comprehensive guide on how to craft such a form:
To start, establish the HTML framework for the multi-step form by creating a container for each step, incorporating input fields and navigation buttons.
<!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>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="form-container">
<div class="step" id="step1">
<label for="name">Name:</label>
<input type="text" id="name" required>
<button type="button" onclick="nextStep(2)">Next</button>
</div>
<div class="step" id="step2" style="display:none;">
<label for="email">Email:</label>
<input type="email" id="email" required>
<button type="button" onclick="previousStep(1)">Previous</button>
<button type="button" onclick="nextStep(3)">Next</button>
</div>
<div class="step" id="step3" style="display:none;">
<label for="phone">Phone:</label>
<input type="tel" id="phone" required>
<button type="button" onclick="previousStep(2)">Previous</button>
<button type="button" onclick="submitForm()">Submit</button>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
Create a custom JavaScript file (script.js) for managing form navigation and validation:
function showStep(stepNumber) {
document.querySelectorAll('.step').forEach(step => {
step.style.display = 'none';
});
document.getElementById(`step${stepNumber}`).style.display = 'block';
}
function nextStep(stepNumber) {
const currentStep = stepNumber - 1;
const inputs = document.getElementById(`step${currentStep}`).querySelectorAll('input');
const allValid = Array.from(inputs).every(input => input.checkValidity());
if (allValid) {
sendDataToEndpoint(currentStep, inputs);
showStep(stepNumber);
} else {
// Display error messages when needed
}
}
function previousStep(stepNumber) {
showStep(stepNumber);
}
function sendDataToEndpoint(stepNumber, inputs) {
const url = `https://example.com/api/step${stepNumber}`;
const data = {};
inputs.forEach(input => {
data[input.id] = input.value;
});
fetch(url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(data),
});
}
function submitForm() {
const inputs = document.getElementById('step3').querySelectorAll('input');
const allValid = Array.from(inputs).every(input => input.checkValidity());
if (allValid) {
sendDataToEndpoint(3, inputs);
// Direct to a success page or display a success message
} else {
// Display error messages when needed
}
}