Solved

# Count checkboxes

Posted on 2013-01-23
255 Views
I have four checkboxes, but not allow none or all to be checked.

<!DOCTYPE html>
<html>
<body>

<form action="">
<input type="checkbox" name="vehicle" value="Bike">I have a bike<br>
<input type="checkbox" name="vehicle" value="Car">I have a car<br>
<input type="checkbox" name="vehicle" value="House">I have a house<br>
<input type="checkbox" name="vehicle" value="Cat">I have a cat <br>
</form>

</body>
</html>
0
Question by:rgbcof

LVL 22

Accepted Solution

Mrunal earned 250 total points
ID: 38813246

``````\$('#btnSubmit').click(function(){
alert('Total : ' + \$('#CHKContainer input:checkbox').length);
alert('Checked : ' + \$('#CHKContainer input:checkbox:checked').length);
});
``````

Reference:

http://jsfiddle.net/HfnqG/
0

LVL 3

Assisted Solution

Khilu earned 250 total points
ID: 38813260
Here is detailed solution

http://jsfiddle.net/rRZfn/1/

``````var countChecked = function() {
var n = \$( "input:checked" ).length;
if(n==0)
{
}

if( \$( "input:checkbox").length== n)
{
alert("Can not select all check box")
}

};

countChecked();

\$( "input[type=checkbox]" ).on( "click", countChecked );
``````
0

LVL 10

Expert Comment

ID: 38813299
var formobj = document.forms[0];

var counter = 0;
Try to findout selected value like this

for (var j = 0; j < formobj.elements.length; j++)
{
if (formobj.elements[j].type == "checkbox")
{
if (formobj.elements[j].checked)
{
counter++;
}
}
}

alert('Total Checked = ' + counter);

With jQuery you can:

\$("input:checkbox:checked").length;
0

## Featured Post

This article shows how to create and access 2-dimensional arrays in JavaScript.  It includes a tutorial in case you are just trying to "get your head wrapped around" the concept and we'll also look at some useful tips for more advanced programmers. …
When you need to keep track of a simple list of numbers or strings, the Array object is your most direct tool.  As we saw in my earlier EE Article (http://www.experts-exchange.com/A_3488.html), typical array handling might look like this: (CODE) B…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…