cypher75 cypher75 - 9 months ago 30
jQuery Question

How can I use required attribute for a group of checkboxes?

I have a group of checkboxes of which at least one has to be checked to submit the form. For this I named each checkbox identically and set the


But this doesn't work:

<input name="mycheckgroup" type="checkbox" value="1" required />
<input name="mycheckgroup" type="checkbox" value="2" required />
<input name="mycheckgroup" type="checkbox" value="3" required />

I have to check all three boxes for submitting the form :-(

If this were radio buttons, it worked... But I want at least one or more boxes to be checked.

Can anyone help?


As I didn't know, that I would need javascript for this solution I didn't tag it, sorry.

But I need it to be checkboxes (no select).

So, here is my working solution using jQuery:

    if($('#cb1').is(':checked') || $('#cb2').is(':checked') || $('#cb3').is(':checked'))
        $(".myCB").attr("required", false);
        $(".myCB").attr("required", true);

<input name="mycheckgroup" id="cb1" type="checkbox" value="1" class="myCB" required />
<input name="mycheckgroup" id="cb2" type="checkbox" value="2" class="myCB" required /> 
<input name="mycheckgroup" id="cb3" type="checkbox" value="3" class="myCB" required />

When checking any checkbox, the required attribute will be removed from all checkboxes in this group.