How many check boxes are checked

I have check buttons on the document.

<input type="checkbox" id="CustmerRequested"/>

I want to know how many of the boxes in the document are checked.

I tried to do alert(document.all.CustmerRequested.checked.length); but it says undefined.

How can I find out how many boxes are checked?

Answers


If you are starting to build a site that needs this kind of browser-side programming reguarly, I would suggest looking at jQuery. See here for tutorials: http://docs.jquery.com/Tutorials

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        $("#someButton").click(function() {
            var checkedBoxes = $("#yourForm input:checked");
            alert(checkedBoxes.length + " checked.");
        });
    });
</script>

Use a Javascript framework like Prototype or JQuery to find the elements you need to check, e.g. In Prototype:

var inputs = $$('input');

This returned array can then looped over to count the number of inputs that are checked checkboxes, like so:

for (var i=0; i<inputs.length; i++){
    if (inputs[i].type == 'checkbox' && inputs[i].checked) {
        numChecked++;
    }
}

Yes, you can do this with JavaScript. No, you don't need jQuery.

Here's one way:

function howManyAreChecked()
{
one = document.getElementById("one").checked;
two = document.getElementById("two").checked;
three= document.getElementById("three").checked;

var checkCount = 0;
if ( one == true )
  { checkCount = checkCount + 1 }
if ( two == true )
  { checkCount = checkCount + 1 }
if ( three == true )
  { checkCount = checkCount + 1 }

alert(checkCount);
}

The example above assumes that you've got 3 checkboxes in HTML, with ids "one", "two" and "three". The script first stores the value of the "checked" property, which can be either TRUE or FALSE. The script then looks at each different variable, and if TRUE, increments the counter.


Need Your Help

create custom LAMP distribution like XAMPP

php c makefile lamp configure

I wish to make a self contained LAMP distro software package from source with at least the following:

MapKit Overlays consuming massive CPU resources

ios overlay mapkit shapefile proj4

I'm overlaying the contents of a third-party shapefile. Some of the polygons consist of 138,000 points, most of them of about 3,000-8,000. In total there are 125 polygons.