简体   繁体   中英

Making at least One Checkbox mandatory out of the given checkboxes on submit

I have the several check boxes inside of the form group. How can I made this Area of Interest checkbox mandatory on submit? At least the user clicks on one checkbox before submitting. I have used react-bootstrap.

Any help are appreciated.

<Form.Group>
    <Form.Label>Area of Interest</Form.Label>
    <Form.Check
        name="areaOfInterest"
        label="Dedicated Teams"
        id="dt"
        value={"Dedicated Teams" || formInput.areaOfInterest}
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Cloud Expert Advice &amp; Support"
        id="ceas"
        value="Cloud Expert Advice &amp; Support"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Software Development"
        id="sd"
        value="Software Development"
        onChange={handleCheck}
    />
    <Form.Check
        name="areaOfInterest"
        label="Digital Transformation"
        id="dit"
        value="Digital Transformation"
        onChange={handleCheck}
    />
</Form.Group>

On form submit you can check the existence of checked checkbox, if there is not any checked you can return false .

Demo:

 function submitForm(){ if(!document.querySelector(':checked')) return false; };
 <form onsubmit="return submitForm()"> <input type="checkbox" id="vehicle1" name="vehicle1" value="Bike"> <label for="vehicle1"> I have a bike</label><br> <input type="checkbox" id="vehicle2" name="vehicle2" value="Car"> <label for="vehicle2"> I have a car</label><br> <input type="checkbox" id="vehicle3" name="vehicle3" value="Boat"> <label for="vehicle3"> I have a boat</label><br> <button>Submit</button> </form>

You can simply check before submitting the form if areaOfInterest has any value to it or not. If it doesn't, show user an error telling them it's a compulsory. If areaOfInterest has even a single response to it, let the form submit.

Depends on how you handle state. I assume you are saving the checkbox's state somehow, like an array or object. One way to do this is to make a function to check the checkbox's state. If it's empty you can disable save or either send an error message.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM