[javascript] Making sure at least one checkbox is checked

I have a form with multiple checkboxes and I want to use JavaScript to make sure at least one is checked. This is what I have right now but no matter what is chosen an alert pops up.

JS (wrong)

function valthis(){
 if (document.FC.c1.checked) {
   alert ("thank you for checking a checkbox")
  } else  {
   alert ("please check a checkbox")
  }
}

HTML

<p>Please select at least one Checkbox</p>
<br>
<br>
<form name = "FC">
<input type = "checkbox" name = "c1" value = "c1"/> C1 
<br>
<input type = "checkbox" name = "c1" value = "c2"/> C2
<br>
<input type = "checkbox" name = "c1" value = "c3"/> C3
<br> 
<input type = "checkbox" name = "c1" value = "c4"/> C4 
<br>
</form>
<br>
<br>

<input type = "button" value = "Edit and Report" onClick = "valthisform();">

So what I ended up doing in JS was this:

function valthisform(){
 var chkd = document.FC.c1.checked || document.FC.c2.checked||document.FC.c3.checked|| document.FC.c4.checked

 if (chkd == true){

 } else {
    alert ("please check a checkbox")
 }

}

I decided to drop the "Thank you" part to fit in with the rest of the assignment. Thank you so much, every ones advice really helped out.

This question is related to javascript html checkbox

The answer is


I would opt for a more functional approach. Since ES6 we have been given such nice tools to solve our problems, so why not use them. Let's begin with giving the checkboxes a class so we can round them up very nicely. I prefer to use a class instead of input[type="checkbox"] because now the solution is more generic and can be used also when you have more groups of checkboxes in your document.

HTML

    <input type="checkbox" class="checkbox" value=ck1 /> ck1<br />
    <input type="checkbox" class="checkbox" value=ck2 /> ck2<br />

JavaScript

function atLeastOneCheckboxIsChecked(){
    const checkboxes = Array.from(document.querySelectorAll(".checkbox"));
    return checkboxes.reduce((acc, curr) => acc || curr.checked, false);
}

When called, the function will return false if no checkbox has been checked and true if one or both is.

It works as follows, the reducer function has two arguments, the accumulator (acc) and the current value (curr). For every iteration over the array, the reducer will return true if either the accumulator or the current value is true. the return value of the previous iteration is the accumulator of the current iteration, therefore, if it ever is true, it will stay true until the end.


Check this.

You can't access form inputs via their name. Use document.getElements methods instead.


You can check that atleast one checkbox is checked or not using this simple code. You can also drop your message.

Reference Link

<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 />

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

Vanilla JS:

var checkboxes = document.getElementsByClassName('activityCheckbox'); // puts all your checkboxes in a variable

function activitiesReset() {
    var checkboxesChecked = function () { // if a checkbox is checked, function ends and returns true. If all checkboxes have been iterated through (which means they are all unchecked), returns false.
        for (var i = 0; i < checkboxes.length; i++) {
            if (checkboxes[i].checked) {
                return true;
            }
        }
        return false;
    }
    error[2].style.display = 'none'; // an array item specific to my project - it's a red label which says 'Please check a checkbox!'. Here its display is set to none, so the initial non-error label is visible instead. 
        if (submitCounter > 0 && checkboxesChecked() === false) { // if a form submit has been attempted, and if all checkboxes are unchecked
            error[2].style.display = 'block'; // red error label is now visible.
        }
}

for (var i=0; i<checkboxes.length; i++) {  // whenever a checkbox is checked or unchecked, activitiesReset runs.
    checkboxes[i].addEventListener('change', activitiesReset);
}


Explanation:
Once a form submit has been attempted, this will update your checkbox section's label to notify the user to check a checkbox if he/she hasn't yet. If no checkboxes are checked, a hidden 'error' label is revealed prompting the user to 'Please check a checkbox!'. If the user checks at least one checkbox, the red label is instantaneously hidden again, revealing the original label. If the user again un-checks all checkboxes, the red label returns in real-time. This is made possible by JavaScript's onchange event (written as .addEventListener('change', function(){});


This should work:

function valthisform()
{
    var checkboxs=document.getElementsByName("c1");
    var okay=false;
    for(var i=0,l=checkboxs.length;i<l;i++)
    {
        if(checkboxs[i].checked)
        {
            okay=true;
            break;
        }
    }
    if(okay)alert("Thank you for checking a checkbox");
    else alert("Please check a checkbox");
}

If you have a question about the code, just comment.


I use l=checkboxs.length to improve the performance. See http://www.erichynds.com/javascript/javascript-loop-performance-caching-the-length-property-of-an-array/


if(($("#checkboxid1").is(":checked")) || ($("#checkboxid2").is(":checked"))
            || ($("#checkboxid3").is(":checked"))) {
 //Your Code here
}

You can use this code to verify that checkbox is checked at least one.

Thanks!!


Prevent user from deselecting last checked checkbox.
jQuery (original answer).

$('input[type="checkbox"][name="chkBx"]').on('change',function(){
    var getArrVal = $('input[type="checkbox"][name="chkBx"]:checked').map(function(){
        return this.value;
    }).toArray();

    if(getArrVal.length){
        //execute the code
        $('#msg').html(getArrVal.toString());

    } else {
        $(this).prop("checked",true);
        $('#msg').html("At least one value must be checked!");
        return false;

    }
});

UPDATED ANSWER 2019-05-31
Plain JS

_x000D_
_x000D_
let i,_x000D_
    el = document.querySelectorAll('input[type="checkbox"][name="chkBx"]'),_x000D_
    msg = document.getElementById('msg'),_x000D_
    onChange = function(ev){_x000D_
        ev.preventDefault();_x000D_
        let _this = this,_x000D_
            arrVal = Array.prototype.slice.call(_x000D_
                document.querySelectorAll('input[type="checkbox"][name="chkBx"]:checked'))_x000D_
                    .map(function(cur){return cur.value});_x000D_
_x000D_
        if(arrVal.length){_x000D_
            msg.innerHTML = JSON.stringify(arrVal);_x000D_
        } else {_x000D_
            _this.checked=true;_x000D_
            msg.innerHTML = "At least one value must be checked!";_x000D_
        }_x000D_
    };_x000D_
_x000D_
for(i=el.length;i--;){el[i].addEventListener('change',onChange,false);}
_x000D_
<label><input type="checkbox" name="chkBx" value="value1" checked> Value1</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value2"> Value2</label>_x000D_
<label><input type="checkbox" name="chkBx" value="value3"> Value3</label>_x000D_
<div id="msg"></div>
_x000D_
_x000D_
_x000D_


< script type = "text/javascript" src = "js/jquery-1.6.4.min.js" >  <  / script >
     < script type = "text/javascript" >

function checkSelectedAtleastOne(clsName) {
    if (selectedValue == "select")
        return false;

    var i = 0;
    $("." + clsName).each(function () {

        if ($(this).is(':checked')) {
            i = 1;
        }

    });

    if (i == 0) {
        alert("Please select atleast one users");
        return false;
    } else if (i == 1) {
        return true;
    }

    return true;

}

$(document).ready(function () {
    $('#chkSearchAll').click(function () {

        var checked = $(this).is(':checked');
        $('.clsChkSearch').each(function () {
            var checkBox = $(this);
            if (checked) {
                checkBox.prop('checked', true);
            } else {
                checkBox.prop('checked', false);
            }
        });

    });

    //for select and deselect 'select all' check box when clicking individual check boxes
    $(".clsChkSearch").click(function () {

        var i = 0;
        $(".clsChkSearch").each(function () {

            if ($(this).is(':checked')) {}
            else {

                i = 1; //unchecked
            }

        });

        if (i == 0) {
            $("#chkSearchAll").attr("checked", true)
        } else if (i == 1) {

            $("#chkSearchAll").attr("checked", false)
        }

    });

});

<  / script >

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

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 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?