I am working on a form in which I have a section of it that needs to have at least one of the checkboxes checked. I am using ReactJS and a React Hook Form.
Here is the checkbox section of code within my render
function:
{/* Checkbox group. User must select at least one medium. */}
<label><b>Medium (check all that apply): *</b></label>
<div>
<label>
<input type="checkbox" name="medium" value="Design & Illustration" onChange="validateMedium();"/><span>Design & Illustration</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Digital Art" onChange="validateMedium();"/><span>Digital Art</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Drawing" onChange="validateMedium();"/><span>Drawing</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Painting & Mixed Media" onChange="validateMedium();"/><span>Painting & Mixed Media</span>
</label>
</div>
<div>
<label>
<input type="checkbox" name="medium" value="Photography" onChange="validateMedium();"/><span>Photography</span>
</label>
</div>
Here is the function I am trying to write to validate the checkbox group:
function validateMedium() {
var mediumCheckboxes = document.getElementsByName("medium");
var okay = false;
for (var i = 0, len = mediumCheckboxes.length; i < len; i++) {
if (mediumCheckboxes[i].checked) {
okay = true;
break;
}
}
if (okay) {
alert("Thank you");
} else {
alert("Please check at least one medium.");
}
}
How do I integrate the validation function I've written specifically for the checkbox group on this form? If the user does not check at least one checkbox when the submit button is clicked, I would like the error to appear. I do not want to use jQuery.
Aucun commentaire:
Enregistrer un commentaire