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 required
attribute.
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?
Without introducing JavaScript the most logical answer to this would be to change your control to a select
element (which is much more appropriate in your situation):
<select>
<option value="1" selected>Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
If this isn't a good enough solution for you then you're going to have to handle the validation with JavaScript. I'm not going to provide a solution here as you don't have javascript tagged and may already know how to do this yourself anyway.
If you do want to use the JavaScript approach you should edit your question to ask for a possible JavaScript solution and include any libraries you use - although in the spirit of StackOverflow you should attempt to resolve this yourself.
No, sorry. I, think you misunderstood. I need possibility to check one or more checkboxes. - cypher75
In that case you can give your select
element the multiple
attribute, allowing you to select more than one option:
<select multiple required>
<option disabled>Select Multiple</option>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
I've added an initial option
element which is disabled
in order for the select
element's required
attribute to take effect.
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:
<script>
$('.myCB').click(function(){
if($('#cb1').is(':checked') || $('#cb2').is(':checked') || $('#cb3').is(':checked'))
$(".myCB").attr("required", false);
else
$(".myCB").attr("required", true);
});
</script>
<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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With