Fast way to validate if all checkboxes are un-selected?

16,518

Solution 1

You have to loop through them. Even a library like jQuery will loop through them, just hide it from you.

var form = document.getElementById('Form2');
var inputs = form.getElementsByTagName('input');
var is_checked = false;
for(var x = 0; x < inputs.length; x++) {
    if(inputs[x].type == 'checkbox' && inputs[x].name == 'us') {
        is_checked = inputs[x].checked;
        if(is_checked) break;
    }
}
// is_checked will be boolean 'true' if any are checked at this point.

Solution 2

jQuery would be a mass of unneeded bloat for a task this trivial. Consider using it if you are running it for other purposes, but all you need is something like this:

function AreAnyCheckboxesChecked () {
  var checkboxes = document.forms.Form2.elements.us;
  for (var i = 0; i < checkboxes.length; i++) {
    if (checkboxes[i].checked) {
      return true;
    }
  }
  return false;
}

Solution 3

JavaScript:

var allischecked = (function(){
  var o = document.getElementById("Form2").getElementsByTagName("input");
  for(var i=0,l=o.length;i<l;i++){
    o[i].type === "checkbox" && o[i].name === "us" && o[i].checked || return false;
  }
  return true;
})();

With jQuery:

var allischecked = ($("#Form2 input:checkbox:not(checked)").length === 0);

Solution 4

In summary, this snipped will return true if all are NOT checked. It bails out as soon as a checked one is found.

var a = document.getElementsByName("us");
for(var i=0; i<a.length; i++)
   if(a[i].checked)
      return false;
return true;

(did not test, but conceptually it is valid)

Share:
16,518
T.T.T.
Author by

T.T.T.

Updated on June 15, 2022

Comments

  • T.T.T.
    T.T.T. almost 2 years

    Is there a quick way or function that would tell me true/false if all check boxes are deselected? Without going through array? (with JS and HTML)

    All my check boxes have the same name...

    <form action="/cgi-bin/Lib.exe" method=POST name="checks" ID="Form2">
        <input type=checkbox name="us" value="Joe" ID="Checkbox1">
        <input type=checkbox name="us" value="Dan" ID="Checkbox2">
        <input type=checkbox name="us" value="Sal" ID="Checkbox3">
    </form>
    
  • Paolo Bergantino
    Paolo Bergantino almost 15 years
    getElementsByName is quirky in IE and a bit in Opera: quirksmode.org/dom/w3c_core.html, I try to just avoid it altogether.
  • Russ Cam
    Russ Cam almost 15 years
    Thanks for the link - not seen that chart before
  • GalacticCowboy
    GalacticCowboy almost 15 years
    +1 for also showing the JQuery version. Yeah, if this is all you want to do, JQuery is overkill. But if you have other validation, AJAX, etc., a one-line test is hard to beat.