Find No. Of Checkboxes using JavaScript
27
May
2013

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript">
function chking()
{
/* For Running jQuery */
var cbs = $("input:checkbox"); //find all checkboxes
var nbCbs = cbs.size(); //the number of checkboxes

var checked = $("input[@type=checkbox]:checked"); //find all checked checkboxes + radio buttons
var nbChecked = checked.size();

/* For Running jQuery */
/* For Running Javascript */

var inputs = document.getElementsByTagName("input"); //or document.forms[0].elements;
var cbs = []; //will contain all checkboxes
var checked = []; //will contain all checked checkboxes
for (var i = 0; i < inputs.length; i++) {
if (inputs[i].type == "checkbox") {
cbs.push(inputs[i]);
if (inputs[i].checked) {
checked.push(inputs[i]);
}
}
}
var nbCbs = cbs.length; //number of checkboxes
var nbChecked = checked.length; //number of checked checkboxes

alert("Total: " + nbCbs);

alert("Checked: " + nbChecked);

/* For Running Javascript */
}
</script>
</head>

<body>
<form method="post" action="">
<input type="checkbox" name="Hobby 1" value="Hobby 1" /> Hobby 1
<input type="checkbox" name="Hobby 2" value="Hobby 2" /> Hobby 2
<input type="checkbox" name="Hobby 3" value="Hobby 3" /> Hobby 3
<input type="checkbox" name="Hobby 4" value="Hobby 4" /> Hobby 4
<input type="checkbox" name="Hobby 5" value="Hobby 5" /> Hobby 5
<input type="button" value="check" onclick="chking();" />
</form>
</body>
</html>
  • 730 View
  • Pin It