4

Is there a way to check a form before submitting it to see if ANY of the checkboxes have been checked in Javascript?

Something like...

function checkboxcheck(){
/*something in here to check name="brands[]" checkbox array?*/
}

Basically I just want it to alert me if 0 checkboxes were selected. 1 or more is required.

I would call this function on submit.

Thanks much!!

NCoder
  • 325
  • 3
  • 10
  • 25
  • have you tried using a framework like jquery? – Victor Feb 01 '11 at 00:48
  • I've heard of it but haven't done anything with jquery before. You think that's the only way to do this? If so can you point me in the right direction? Thanks! – NCoder Feb 01 '11 at 00:56
  • NCoder: You don't have to use jQuery, it just makes life a lot easier in JS. Pointy's function below could be represented as: `($('input:checkbox:checked').length > 0)` – Orbling Feb 01 '11 at 01:08

2 Answers2

2

You could do something like this:

function anyCheckboxesChecked() {
  var inputs = document.getElementsByTagName('input');
  for (var i = 0; i < inputs.length; ++i) {
    if (inputs[i].type === "checkbox" && inputs[i].checked)
      return true;
  }
  return false;
}

Then you could call that function from your "submit" handler"

   if (!anyCheckboxesChecked()) {
     alert("Please check one of the appealing checkboxes on the page");
     return false;
   }

If your page is more complicated than what this implies (like, if there are multiple forms), then you'd find the appropriate form first and call .getElementsByTagName() from that point instead of from document.

Pointy
  • 405,095
  • 59
  • 585
  • 614
0

How about:

function checkboxcheck(name) {
    var els = document.getElementsByName(name);

    for (var i = 0; i < els.length; i++) {
        if (els[i].checked) {
            return true;
        }
    }
    return false;
}

using getElementsByName().

Usage:

var valid = checkboxcheck("brands[]");

Here's an example: http://jsfiddle.net/andrewwhitaker/2saJp/1/

Andrew Whitaker
  • 124,656
  • 32
  • 289
  • 307