Hi I have a multiple step form, divided by .step-box
. I don't want the user to get to the next step when fields are left empty. So that when you click on .next
, that the form will show which fields are still required. I can access all inputs,selects,radios and checkboxes via stepBoxes[stepIndex].querySelectorAll('input, select')
.
const nextBtns = document.querySelectorAll('.next-btn');
const stepBoxes = document.querySelectorAll('.step-box');
const backBtn = document.querySelector('.back-btn');
const stepCircles = document.querySelectorAll('.step-circle');
let stepIndex = 0;
nextBtns?.forEach((nextBtn) => {
nextBtn.addEventListener('click', (e) => {
e.preventDefault();
stepBoxes[stepIndex].classList.add('hide');
let inputs = stepBoxes[stepIndex].querySelectorAll('input, select');
stepCircles[stepIndex].classList.remove('active');
stepIndex++;
stepBoxes[stepIndex].classList.remove('hide');
stepCircles[stepIndex].classList.add('active');
backBtn.classList.toggle("hide", stepIndex == 0);
});
});
I tried looping through the fields per step which kinda worked out with a select and a regular text input field. just by looping through them and adding an .invalid
class to the ones which are required. It worked out for the regular inputs and select boxes, but not for the radios/checkboxes. Since you've got multiple per item.
I was wondering if someone had a vanilla JS idea on how to do this in a proper way.
Specific text inputs, select boxes and radio groups need to be required. For checkboxes I don't really mind since those are optional.
EDIT:
I currently created a specific form per step, where I added the required attribute to the required fields.
const membershipForm = document.getElementById('membershipForm');
membershipForm?.addEventListener('submit', (e) => {
e.preventDefault();
const formData = new FormData(membershipForm);
for (const pair of formData.entries()) {
jsonObject[pair[0]] = pair[1];
}
console.log(jsonObject);
});