Javascript Select All Checkboxes

Ok so last week I was trying to implement Check ALL / Unckeck ALL functionality. The form was having a root checkbox and by selecting this checkbox all the checkboxes on form should also be selected. Same for uncheck all should be unchecked.

There are many code snippets available but the problem was I was submitting this form to a PHP script and to process the checked entires PHP needs an array. So the checkboxes name should be something like chktopic[],

<input type="checkbox" name="chktopic[]” value=”topic_1″ />
<input type="checkbox" name="chktopic[]” value=”topic_2″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_3″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_4″ />
<input type=”checkbox” name=”chktopic[]” value=”topic_5″ />

and then in PHP script you can use it like

$topics = $_POST[“chktopic”];
$totaltopics = count($topics);
for ($i=0; $i<$totaltopics; $i++) {
$status = deleteTopic($topics[$i]);

You can see I am trying to Delete all the selected topics. That was the PHP part but how about JavaScript how we will implement check all / uncheck all. So initially I tried with is function

My root checkbox

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics.chktopic,this)”>

and the JS function was

function checkAll(checkname, root) {
for (i = 0; i < checkname.length; i++)
checkname[i].checked = root.checked? true:false

But this function was not working as you can see the name is having [] (an array), if you use a single name (like name=”chktopic”) for all checkboxes this function will work smoothly but then PHP will refuse, as PHP needs an array.

So to handle this situation we will use the same JavaScript function but on root checkboxes we will do a tweak

<input type=”checkbox” name=”all” title=”Select All” onClick=”checkAll(document.form_topics[‘chktopic[]’],this)”>

Simple right 🙂