[html] How can I require at least one checkbox be checked before a form can be submitted?

I have a list of multiple check boxes. The user can check all of them, but at least one should be checked to allow form submission. How can I enforce that requirement?

<p>Box Set 1</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>
<p>Box Set 2</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 5" required><label>Box 5</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 6" required><label>Box 6</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 7" required><label>Box 7</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 8" required><label>Box 8</label></li>
</ul>
<p>Box Set 3</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 9" required><label>Box 9</label></li>
</ul>
<p>Box Set 4</p>
<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 10" required><label>Box 10</label></li>
</ul>

This question is related to html css validation checkbox

The answer is


The issue with the accepted solution above is that is does not allow for the else condition on form submit (if a box has been selected), thereby preventing form submission - at least when I tried it.

I discovered another solution that effects the desired result more completely IMHO, here:

Making sure at least one checkbox is checked

Code as follows:

function valthis() {
var checkBoxes = document.getElementsByClassName( 'myCheckBox' );
var isChecked = false;
    for (var i = 0; i < checkBoxes.length; i++) {
        if ( checkBoxes[i].checked ) {
            isChecked = true;
        };
    };
    if ( isChecked ) {
        alert( 'At least one checkbox checked!' );
        } else {
            alert( 'Please, check at least one checkbox!' );
        }   
}

Fiddle

That code & answer by Vell


Using this you can check at least one checkbox is selected or not in different checkbox groups or multiple checkboxes.

Reference : Link

<label class="control-label col-sm-4">Check Box 1</label>
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Male /> Male<br />
    <input type="checkbox" name="checkbox1" id="checkbox1" value=Female /> Female<br />

<label class="control-label col-sm-4">Check Box 2</label>
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck1 /> ck1<br />
    <input type="checkbox" name="checkbox2" id="checkbox2" value=ck2 /> ck2<br />

<label class="control-label col-sm-4">Check Box 3</label>
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck3 /> ck3<br />
    <input type="checkbox" name="checkbox3" id="checkbox3" value=ck4 /> ck4<br />

<script>
function checkFormData() {
    if (!$('input[name=checkbox1]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 1 can not be null";
        return false;
    }
    if (!$('input[name=checkbox2]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 2 can not be null";
        return false;
    }
    if (!$('input[name=checkbox3]:checked').length > 0) {
        document.getElementById("errMessage").innerHTML = "Check Box 3 can not be null";
        return false;
    }
    alert("Success");
    return true;
}
</script>

This should have what you need, check out the jsfiddle at the bottom:

$(document).ready(function () {
$('#txt').val($("input[type=checkbox]:checked").length);
$('#txt2').val($("input[type=checkbox]").length);

$('input[type=checkbox]').change(function () {
checked = $("input[type=checkbox]:checked").length;
$('#block').show();
$('#block2').hide();
if (checked > 0) {
  $('#block').hide();
  $('#block2').show();
  $('#txt').val(checked);
 }
});
});

You can either do this on a PHP level or on a Javascript level. If you use Javascript, and/or JQuery, you can check and validate if all the checkboxes are checked with a selector...

Jquery also offers several validation libraries. Check out: http://jqueryvalidation.org/

The problem with using Javascript to validate is that it may be bypassed so it is wise to check on the server too.

Example using PHP and assuming you are calling a PO

<?php
    if( $_GET["BoxSelect"] )
 {
     //Process your form here
     // Save to database, send email, redirect...
} else {

     // Return an error and do not anything
     echo "Checkbox is missing"; 


     exit();
 }
?>

For php, when you use checkboxes for multiple values, the name always ends with []. We can use this to make the solution a bit more generic. And, since I put my error message in a data-message-value-missing attribute, I use:

$form.on('change', 'input[type=checkbox][name$="[]"]', e => {
    const $inputs = $('input[type=checkbox][name="' + e.target.name + '"]');
    const $targetInp = $inputs.filter('[data-message-value-missing]');
    if($inputs.filter(':checked').length) {
        $targetInp.removeAttr('required');
        $form.find('label.error').html('');
    } else {
        $targetInp.attr('required', 'required');
    }
});

To make this work, set the data-message-value-missing and the required on only one (the last) input:

<ul>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 1"><label>Box 1</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 2"><label>Box 2</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 3"><label>Box 3</label></li>
   <li><input name="BoxSelect[]" type="checkbox" value="Box 4" required data-message-value-missing="Select at least one"><label>Box 4</label></li>
</ul>

I excluded the code to handle the checkValidity(), etc. Seems beyond the scope of this question...


<ul>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 1" required><label>Box 1</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 2" required><label>Box 2</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 3" required><label>Box 3</label></li>
    <li><input class="checkboxes" name="BoxSelect[]" type="checkbox" value="Box 4" required><label>Box 4</label></li>
</ul>

<script type="text/javascript">
$(document).ready(function(){
    var checkboxes = $('.checkboxes');
    checkboxes.change(function(){
        if($('.checkboxes:checked').length>0) {
            checkboxes.removeAttr('required');
        } else {
            checkboxes.attr('required', 'required');
        }
    });
});
</script>

Make all the checkboxes required and add a change listener. If any one checkbox is ticked, remove required attribute from all the checkboxes. Below is a sample code.

<div class="form-group browsers">
    <label class="control-label col-md-4" for="optiontext">Select an option</label>
    <div class="col-md-6">
        <input type="checkbox" name="browser" value="Chrome" required/> Google Chrome<br>
        <input type="checkbox" name="browser" value="IE" required/> Internet Explorer<br>
        <input type="checkbox" name="browser" value="Mozilla" required/> Mozilla Firefox<br>
        <input type="checkbox" name="browser" value="Edge" required/> Microsoft Edge
    </div>
</div>

Change listener :

$(function(){
    var requiredCheckboxes = $('.browsers :checkbox[required]');
    requiredCheckboxes.change(function(){
        if(requiredCheckboxes.is(':checked')) {
            requiredCheckboxes.removeAttr('required');
        } else {
            requiredCheckboxes.attr('required', 'required');
        }
    });
});

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to css

need to add a class to an element Using Lato fonts in my css (@font-face) Please help me convert this script to a simple image slider Why there is this "clear" class before footer? How to set width of mat-table column in angular? Center content vertically on Vuetify bootstrap 4 file input doesn't show the file name Bootstrap 4: responsive sidebar menu to top navbar Stylesheet not loaded because of MIME-type Force flex item to span full row width

Examples related to validation

Rails 2.3.4 Persisting Model on Validation Failure Input type number "only numeric value" validation How can I manually set an Angular form field as invalid? Laravel Password & Password_Confirmation Validation Reactjs - Form input validation Get all validation errors from Angular 2 FormGroup Min / Max Validator in Angular 2 Final How to validate white spaces/empty spaces? [Angular 2] How to Validate on Max File Size in Laravel? WebForms UnobtrusiveValidationMode requires a ScriptResourceMapping for jquery

Examples related to checkbox

Setting default checkbox value in Objective-C? Checkbox angular material checked by default Customize Bootstrap checkboxes Angular ReactiveForms: Producing an array of checkbox values? JQuery: if div is visible Angular 2 Checkbox Two Way Data Binding Launch an event when checking a checkbox in Angular2 Checkbox value true/false Angular 2: Get Values of Multiple Checked Checkboxes How to change the background color on a input checkbox with css?