I'm building a multiple step form, using mostly JS.
I have a next button with a click event. Which should loop through all fields and validate them. I think I can just loop through the fields and check if they are not empty and/or match a specific regex. But I have no clue on how to validate radio buttons/checkboxes in a loop.
For example. I have 3 radio buttons that belong to eachother. But the inputs selector thinks that there are 3 inputs. Which is technically true. I tried using the :checked property, but again, I didn't really know how to perform that action in a loop.
And ofcourse at a specific step, when the validation fails, it should return a variable with false, to prevent the script from going to the next step.
TL;DR: I build a step form, but I have trouble making the input validation work per step within a loop.
const nextBtn = document.getElementById('next');
const steps = document.querySelectorAll('steps');
let currentIndex = 0;
nextBtn.addEventListener('click', (e) => {
e.preventDefault();
const fields = steps[currentIndex].querySelectorAll('input');
steps[currentIndex].classList.add('hide');
steps[currentIndex++].classList.remove('hide');
});
.hide {
display: none;
}
<div class="steps" id="step1">
<input type="text" name="fname" id="fname">
Option 1<input type="radio" name="options" id="option1" value="option1">
Option 2<input type="radio" name="options" id="option2" value="option2">
Option 3<input type="radio" name="options" id="option3" value="option3">
</div>
<div class="steps hide" id="step2">
<input type="text" name="lname" id="lname">
Red<input type="checkbox" name="colors[]" id="red" value="red">
Blue<input type="checkbox" name="colors[]" id="blue" value="blue">
Green<input type="checkbox" name="options[]" id="green" value="green">
</div>
<button id="next">Next</button>