htmlformscheckbox

Can we group the check box in html


I have a basic question about html. I know when we are using radio button we can group several buttons by giving them the same "name" attribute, i.e. only one of them can be selected. e.g.:

<p> example
<input type="radio" name="example" value="option 1"> option 1
<input type="radio" name="example" value="option 2"> option 2
<input type="radio" name="example" value="option 3"> option 3</p>

So in the example, user can only choose one among option 1, option 2, option 3. My question is whether we can do the same thing for checkbox?


Solution

  • No. Checkboxes are meant to be selected independently. That's why both checkboxes and radio elements exist. It's not just for different appearance.

    However, it's common approach to group checkboxes by name, using array-like convention:

    <input type="checkbox" name="example[]" value="option 1"> option 1
    <input type="checkbox" name="example[]" value="option 2"> option 2
    

    Form sent that way will be parsed by the server-side language as one array of checked elements.