Wednesday, March 25, 2009

Javascript for Checkbox array

I have searched so many javascripts for writing a code for the checkbox array example "< input type="checkbox" name="check[]" >" But i could not find a single javascript. You will get so many scripts for a simple checkbox with name "check" , which can be found with a simple search, But this type of scenario's cannot be found easily. So we are updating the javascript so that you can use it when needed.

<html>
<head>

<script language="javascript">
function anyCheck(form) {
var total = 0;
var max = document.playlist.elements['ckbox[]'].length;
alert(max);
for (var idx = 0; idx < max; idx++) {
if(document.playlist.elements['ckbox[]'][idx].checked==true){
total += 1;
//alert(total);
}
//alert('ns');
}
alert("You selected " + total + " boxes.");
}
</script>
</head>
<body>

<form method="post" name=playlist>
1<input type=checkbox name=ckbox[]>
<brɮ<input type=checkbox name=ckbox[]>
<brɯ<input type=checkbox name=ckbox[]>
<brɰ<input type=checkbox name=ckbox[]>
<brɱ<input type=checkbox name=ckbox[]>
<brɲ<input type=checkbox name=ckbox[]>
<brɳ<input type=checkbox name=ckbox[]>
<brɴ<input type=checkbox name=ckbox[]>
<brɵ<input type=checkbox name=ckbox[]>
<p><input type=button value="Count Checkboxes" onClick="anyCheck(this.form)">
</form>


</body>
</html>

Here the method is used is anyCheck(). Which will invoke the javascript method. When we invoke the javascript method document.playlist.elements['ckbox[]'].length will calculate the length of the checkbox array value and if condition will evaluate which checkbox is checked and returns the total count.

No comments:

Post a Comment