How to : Select or Unselect all checkboxes using javascript

0saves

Introduction

There are cases where we want to select all the checkboxes or unselect all the checkboxes, but their count are so many that we get irritated. Our users of the website or the system might feel the same thing. So whats the best solution : A checkbox which says select all and unselect all the options.

Description

Below code is a combination of Javascript and HTML, which represents a mechanism to select all the checkboxes and unselect all the checkboxes.

Benefits

1) A single checkbox to select all the checkboxes
2) A single checkbox to deselect all the checkboxes
3) There can be any number of check boxes, there is no restriction on the number of check boxes.

Code


<script type="text/javascript">
var checked=false;
var frmname='';
function checkedAll(frmname)
{
 var valus= document.getElementById(frmname);
 if (checked==false)
 {
 checked=true;
 }
 else
 {
 checked = false;
 }
 for (var i =0; i < valus.elements.length; i++)
 {
 valus.elements[i].checked=checked;
 }
}
</script>
<form id ="cbexample">
<input type="checkbox" name="chk1">Apple
<input type="checkbox" name="chk2">Banana
<input type='checkbox' name='checkall' onclick='checkedAll("cbexample");'>Select All
</form>

Demo
Download

If you enjoyed this post, please consider leaving a comment or subscribing to the RSS feed to have future articles delivered to your feed reader.

Related Posts

About the Author: Abhishek Sanghvi

Hi Friends, my name is Abhishek Sanghvi and I am the founder of this “open source script” site MYPHPSCRIPTZ. I have been learning and practising PHP from the last 3 years. You could always contact me if you wish to have some code for your need. I would surely try and solve them for you at abhishek(at)myphpscriptz(dot)com

9 Comments + Add Comment

Leave a comment


two + one =

CommentLuv badge