Monday, August 8, 2011

count of checkboxes selected using javascript

Below is the code to know the number of checkboxes selected in a form. The function returns the total count of the Checkbox checked.

<script type="text/javascript">
function anyCheck(form) {
var total = 0;
var Count = document.playlist.count.value;
for (var idx = 1; idx < Count; idx++) {
if (eval("document.playlist.ckbox" + idx + ".checked") == true) {
total += 1;
}
}
alert("You selected " + total + " boxes.");
}
</script>
<form method="post" name=playlist>
1<input type=checkbox name=ckbox>
<br>2<input type="checkbox" name="ckbox1" onchange="anyCheck(this.value)">
<br>3<input type="checkbox" name="ckbox2" onchange="anyCheck(this.value)">
<br>4<input type="checkbox" name="ckbox3" onchange="anyCheck(this.value)">
<br>5<input type="checkbox" name="ckbox4" onchange="anyCheck(this.value)">
<br>6<input type="checkbox" name="ckbox5" onchange="anyCheck(this.value)">
<br>7<input type="checkbox" name="ckbox6" onchange="anyCheck(this.value)">
<br>8<input type="checkbox" name="ckbox7" onchange="anyCheck(this.value)">
<br>9<input type="checkbox" name="ckbox8" onchange="anyCheck(this.value)" >
<input type="hidden" value="8" name="count">
</form>


No comments: