I am trying to created a checkbox, on clicking which select all other checkboxes in react hook form, and on unchecking it will deselect all checkboxes. I also want to add selecting single checkbox feature also.
But I am confused how to do that.
I am trying using UseFieldArray and based on if value of selectAll checkbox is true, I am adding all other checkboxes. But it’s not working. Could you please help with this If I am doing correct or I need go some other way like using onchange method, or append and remove methods to update checked value of checkbox. So
const {
fields: agreementfields,
append: agreementappend,
remove: agreementremove,
} = useFieldArray({ control, name: "agreementitem" });
<input
type="checkbox"
value="true"
{...register("agreementall", {
required: "Agreement is required",
validate: {
isall: (cvalue) => {
if (cvalue) {
setValue("agreementfields", ["checkbox1value", "checkbox2value"]);
} else {
setValue("agreementfields", [""]);
}
},
},
})}
/>
<input
type="checkbox"
value="checkbox1value"
checked={agreementfields.includes("checkbox1value")}
{...register("agreement2", {
required: "Agreement2 is required",
})}
/>
<input
type="checkbox"
value="checkbox2value"
checked={agreementfields.includes("checkbox2value")}
{...register("agreement3", {
required: "Agreement3 is required",
})}
/>
I am trying to created a checkbox, on clicking which select all other checkboxes in react hook form, and on unchecking it will deselect all checkboxes. I also want to add selecting single checkbox feature also.
Ekas Singh is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.