Check one, check all Javascript
Ever since getting “ever so involved” with the DOM in the beginning of this year, I’ve had the aching habit of going through all my old “copy & paste” scripts and rewriting them myself. So, this entry is only a fraction of the outcome of what has been happening to me thus far.
The Scenario
A form with tabularized items generated from a database. Each item has a checkbox in it’s particular row holding an array name for its name attribute and a unique ID for its value. At the top of the form is a stand-alone checkbox which triggers a “check all - check none” event. To top it all off, we need some server side action goin’ on to remove the items that are checked.
The old way
Before moving ahead I thought it would a good idea to show the previous script which I was borrowing from Invision Power Board. This involved two functions that worked together very nicely. Right about now would be a good time to set the style sheet view to “UnDesigned,” and if of course you like to jump ahead to the demo, I’ll let you do that.
Invisionboard Checkall Functions
//==========================================
// Check All boxes
//==========================================
function CheckAll(fmobj) {
for (var i=0;i<fmobj.elements.length;i++) {
var e = fmobj.elements[i];
if ( (e.name != 'allbox') && (e.type=='checkbox') && (!e.disabled) ) {
e.checked = fmobj.allbox.checked;
}
}
}
//==========================================
// Check all or uncheck all?
//==========================================
function CheckCheckAll(fmobj) {
var TotalBoxes = 0;
var TotalOn = 0;
for (var i=0;i<fmobj.elements.length;i++) {
var e = fmobj.elements[i];
if ((e.name != 'allbox') && (e.type=='checkbox')) {
TotalBoxes++;
if (e.checked) {
TotalOn++;
}
}
}
if (TotalBoxes==TotalOn) {
fmobj.allbox.checked=true;
}
else {
fmobj.allbox.checked=false;
}
}
Okay, so as you can see, it really isn’t all that bad. A solid group of functions. One for the checkAll, and one for the body of generated items.
Here is how I revised it, or better yet, came up with by the best of my ability.
Revised CheckAll Function
function checkAll(ref) {
var chkAll = document.getElementById('checkAll');
var checks = document.getElementsByName('del[]');
var removeButton = document.getElementById('removeChecked');
var boxLength = checks.length;
var allChecked = false;
var totalChecked = 0;
if ( ref == 1 ) {
if ( chkAll.checked == true ) {
for ( i=0; i < boxLength; i++ ) {
checks[i].checked = true;
}
}
else {
for ( i=0; i < boxLength; i++ ) {
checks[i].checked = false;
}
}
}
else {
for ( i=0; i < boxLength; i++ ) {
if ( checks[i].checked == true ) {
allChecked = true;
continue;
}
else {
allChecked = false;
break;
}
}
if ( allChecked == true ) {
chkAll.checked = true;
}
else {
chkAll.checked = false;
}
}
for ( j=0; j < boxLength; j++ ) {
if ( checks[j].checked == true ) {
totalChecked++;
}
}
removeButton.value = "Remove ["+totalChecked+"] Selected";
}
Basically, I combined both functions into one with the only difference being a number that gets passed into the function as an argument. For the main checkAll checkNone button (at the top or bottom of your form), you pass in the number “1″, and for everything else, you could pass in whatever you want, as long as it’s not 1. Preferably something like “2″ would suffice.
You’ll also notice in my nifty function that I added a “Remove totalChecked Selected” feature which displays the amount of checked boxes. I suppose if you wanted you could add in another conditional statement which asks if they’re all checked and display “Remove All” instead of displaying a number.
Removing Records with PHP
This part I knew I could definitely improve on. Previously, without the flexibility of putting in unique values for the value=”" attribute, this is how I managed to get them out of the database.
PHP Drop Record Database call
<?php
if ( isset($_POST['remove_selected']) ) {
$q = mysql_query('select id from table');
while ( $r = mysql_fetch_array($q) ) {
$message_id = 'msgid_'.$r['id'];
if ( $$message_id == "yes" ) {
$del_id = $r['id'];
$drop_sql = mysql_query(
"DELETE FROM table
WHERE id = '$del_id'
LIMIT 1");
if ( ! @$drop_sql ) {
die ('Unable to Execute the drop query '.mysql_error());
}
}
}
}
?>
Boy that’s ugly. Notice the second mysql_query() encapsulated within the while() loop. Mhmm, not good. Anytime you’re running loops that send off queries is a potential cause for a database disaster. If you had 50 items to delete, then count on 50 queries being sent to the database server. Fortunately in my case I’ve never had to delete so many items at once. However even 5 queries is too much…and dare I say, even 2 is too much.
The case is IN
With the javascript now being able to intake the database ID’s directly into the value attribute of the checkbox, we can now rewrite our drop script as follows:
Using the SQL ‘IN’ clause to run faster queries
<?php
if ( isset($_POST['remove_selected']) ) {
$postCount = count($_POST['delAnn']);
for ( $i=0; $i < $postCount; $i++ ) {
$deleteIds .= $_POST['del'][$i].',';
}
$deleteIds = rtrim($deleteIds,',');
mysql_query('delete from table where id in ('.$deleteIds.')');
}
?>
Yep. It really is that easy. Not that you’ve already been doing this already. Sometimes I just tend to be a little behind the times. I used to think the longer and more complicated the script was, the better programmer I would be reveered for. *Cough B.S.*
With the above function, all you’re doing is gathering the ids, storing them in a comma delimitted string (not array), remove the last comma with rtrim(), then using mysql’s keyword “IN” to delete specific id’s.
With all this said and done, view the JS CheckAll demo to play around with yourself.




April 9th, 2005 at 3:11 pm
I find it curious that (even) talented coders have a tendency to just write code and avoid doing much to optimise it. Lately, I’ve been going through the code I’m using and squeezing as much crud out as I possibly can. As an example - I use Trillian for my instant messaging. The average skin (for the format I use) is at least 1M in size. Thus far, I’ve done two skins, and both are less than 30k. Admittedly, I’ve taken out the stuff I don’t need, but that’s still quite a difference.
I’ve come to have a bit of a fascination with making as many clever hacks as possible - combining things, rearranging the order, anything that’ll do what I need in a better way.
Ranting done. :)
April 9th, 2005 at 4:59 pm
Hey Dustin, sample doesn’t work in Firefox :(
Tried on Windows and Mac, Javascript errors. It’s probably something simple and a quick fix, it usually is.
April 9th, 2005 at 5:05 pm
The Javascript files aren’t were the SRC attribute says they are, thats an easy one.
April 9th, 2005 at 5:31 pm
I noticed that too, but didn’t take the time to check what was causing it…
April 9th, 2005 at 6:46 pm
whoopsies…it was working on localhost, must have messed something up when I uploaded it to the basement. thanks for the quick catch guys, I appreciate it!
April 9th, 2005 at 6:48 pm
*Update*
I just forgot to upload the two external js files.
Again, thanks! :)
April 9th, 2005 at 7:09 pm
Works beautifully!
April 11th, 2005 at 10:03 pm
great!
// bookmarked it!
April 20th, 2005 at 10:46 am
back from Cali!
Someday I am going to catch up to you and your progressive programming D man! lol…
June 12th, 2005 at 10:08 pm
it’s the good script
July 10th, 2005 at 6:19 am
Search the web for hours for something like this… You’re a life saver. TY
August 23rd, 2005 at 8:50 pm
Does your code work when there is only one checkbox? Other “Check All” button does not work for one checkbox.
Thanks.
Hannie
August 23rd, 2005 at 10:52 pm
Yes. It does.
November 30th, 2005 at 4:39 pm
Why create a string variable when we can use the array $_POST['del'] :DWhat about this php code to delete :
if ( isset($_POST['remove_selected']) ) {Yeah i know it’s out of topic, but i’ve noticed some weird behavior with the isset function and array. Instead of isset($_POST['remove_selected']) i would use array_key_exists(’remove_selected’, $_POST)$deleteIds = implode(’,', $_POST['del']);
mysql_query(’delete from table where id in (’.$deleteIds.’)');
}
And i may be wrong (probably i am) but why not just check $_POST['del'] and the count of elements instead of checking $_POST['remove_selected'] ? I dont see the point to check a variable and user another one.
if (array_key_exists('del', $_POST) && count($_POST['del']) > 0 ) {$deleteIds = implode(’,', $_POST['del']);
mysql_query(’delete from table where id in (’.$deleteIds.’)');
}
November 30th, 2005 at 4:41 pm
wow, sorry but the previsualisation wasn’t showing me my comment as it is now. Sorry for the noise, pretty much unreadable :(
December 13th, 2005 at 2:47 am
An easier alternative & works cross browser.
var checkflag = “false”;
function checkall(field)
{
if (checkflag == “false”)
{
for (i = 0; i
December 16th, 2005 at 7:14 am
How you are deleting from the databse?
I mean.. I did a test, with your code, but when delete just delete one option listed and not all selected (If want to delete all), just the selected option.
Can you help me please?
Thanks
Kisses from Brazil
January 14th, 2006 at 4:35 pm
You may want to add “AddSlashes()” to the php part - the way it is you’re asking for an SQL injection attack.
January 14th, 2006 at 7:04 pm
Jenni, good call. I forgot to mention the deal about
mysql_real_escape_string()that needs to go into every sql query.February 23rd, 2006 at 2:03 pm
Ugh.. I guess I did something wrong before.. Seems like my message got deleted.
Well, what I said was that instead of having an if/else in the first for loop(The one that checks/unchecks all boxes) you could simply set all the boxes to the same state as the “master” box.
e.g. change these lins:
// edited by author ( please link to code offsite :) )
February 23rd, 2006 at 5:05 pm
Duh, I did that before! :P
Well my script is located here: http://www.hutlihut.org/checkall.htm if anyone is interested in it.
Cheers
April 3rd, 2006 at 1:18 am
I AM A FRESHER.I DON’T NOW JAVASCRIPT. THIS IS VERY HELPFUL MOTIVE IF YOU MAIL ME THAT HOW CAN I SET THIS SCRIPT IN A PHP PAGE.
July 3rd, 2006 at 11:35 pm
Hi Dustin can we expect javascript which generates rows dynamically on Clicking on a link “New” and Deletes the rows on Clicking “Delete”. The deletion is based on the checkbox selection.
Thanks
Dev
July 17th, 2006 at 11:56 pm
istead of:
if ( chkAll.checked == true )
why don’t you just do this:
if ( chkAll.checked )
?
October 8th, 2006 at 10:14 pm
In my page, I am having check boxes with in a table and also outside the table.If I use the above function, it selects all the checkboxes even the boxes which are outside of the table.But i want to select only the boxes which are with in the table.How to do it?
October 18th, 2006 at 6:09 am
Great Code thanks!
December 2nd, 2006 at 5:38 am
Nice article!
A little addition, when dealing with database record deletion, it is always wise to use a confirmation dialog box before processing the deletion script, to avoid users accidentally clicking the delete button.
A nice way of doing this:
The delete button should be like this:
And the javascript part:
function confirmDelete()
{
var delete=confirm(”Delete selected record?”);
if (delete)
return true ;
else
return false ;
}
Notice the “return” in the onclick event of the submit button. Without the “return”, the script will execute regardless of the action, whether it is “yes” or “no”.
December 2nd, 2006 at 7:55 am
Hello skatjes van me,
It could me much easier than in the explained way above:
Please check this link: http://www.phpfreaks.com/quickcode/Checking-all-checkboxes-in-a-form/311.php
Good luck darlings
December 2nd, 2006 at 5:34 pm
Btw, Dustin. I’ve noticed that your example doesn’t check the state of any checkbox before the execution. I’ve left all the checkbox unchecked, and click on the “Remove Selected” button and it does execute. How do i make sure that if no checkbox were checked, it should alert a message “Please select a least one record to delete!” and of course halt the execution.
Thank you.
January 2nd, 2007 at 11:46 pm
We’ve been looking for something like this for about two years. Using a single button to check or uncheck all was easy.
But, for our web-based application which can be used to send messages to up to 10,000 individuals, the different solutions for using a checbox to identify whether all were ticked or not tended to be quite slow. This one seems to be quite fast. How come?
(In any case we’re going to use it — thanks)
January 3rd, 2007 at 2:27 am
One other thing… how about if all the check boxes are ticked by default. i.e. how could a check be made when the page is loaded as opposed to when a box ist ticked.
February 22nd, 2007 at 12:25 pm
This is so close to what I need! I’ve got a table with two columns of checkboxes. I want to be able to tick a box atop each to affect just that column.
Well, actually, I want to be able to have a button that will affect the checked state of only certain boxes in a column, depending on whether the box name appears in an array. But that’s Phase II.
February 23rd, 2007 at 9:56 pm
Hey, I tried to use your code - it’s been a while since I have used javascript and I needed to get back into it. You didn’t post the HTML that works with your code and I found that using one function can be a little awkward and it’s not as flexible as the three I created since I couldn’t get yours to work in five minutes (that’s my limit right now - very busy).
My code is as follows and shows the entire page:
I hope this helps someone!
February 23rd, 2007 at 9:58 pm
argh - I used pre tags. It still stripped out my code.
Here’s my code again… :(
<html>
<head>
<script language="JavaScript" type="text/javascript">
<!–
//Accepts two parameters: The first of which is the check_all_box - it should be a FIELD level reference to your checkbox (not a form or a checked status or a value). If you use the onchange method to switch it like I do then all you need to do is pass the ‘this’ keyword to it. See my example below.
//Parameter two is the obj_set_name which is the name of the "object set" or the name you use for your checkbox list. This is what allows the use of multiple lists on one page.
function switchSetting(check_all_box, obj_set_name)
{
var selection_status = check_all_box.checked;
//This is weird because intuitivly, once you click it the first time it would be true - for some reason javascript hasn’t yet registered the click so it still thinks it is false.
//This also occurs if the box is already checked - javascript still thinks its checked even after you click it.
if(selection_status == false)
{
uncheckAll(obj_set_name);
}
else
{
checkAll(obj_set_name);
}
}
function checkAll(obj_set_name)
{
var checkboxes = document.getElementsByName(obj_set_name);
var total_boxes = checkboxes.length;
for(i=0; i<total_boxes; i )
{
current_value = checkboxes[i].checked;
if(current_value == false)
{
checkboxes[i].checked = true;
}
}
}
function uncheckAll(obj_set_name)
{
var checkboxes = document.getElementsByName(obj_set_name);
var total_boxes = checkboxes.length;
for(i=0; i<total_boxes; i )
{
current_value = checkboxes[i].checked;
if(current_value == true)
{
checkboxes[i].checked = false;
}
}
}
//–>
</script>
</head>
<body>
<form action=’#’ method=’post’>
Select All of Set One:<input type=’checkbox’ onchange=’javascript:switchSetting(this, "name[]");’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’one’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’two’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’three’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’four’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’five’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’six’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’6′ /><br />
<input type=’checkbox’ name=’name[]‘ value=’seven’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’random_value’ /><br />
<input type=’checkbox’ name=’name[]‘ value=’my_member_id’ /><br /><br />
Select All of Set Two:<input type=’checkbox’ onchange=’javascript:switchSetting(this, "name2[]");’ /><br />
<input type=’checkbox’ name=’name2[]‘ /><br />
<input type=’checkbox’ name=’name2[]‘ /><br />
<input type=’checkbox’ name=’name2[]‘ /><br />
<input type=’checkbox’ name=’name2[]‘ /><br />
</form>
</body>
</html>
April 11th, 2007 at 12:57 am
Hi,
i was wondering if you could let me know how i can use this function in datagrid of Dotnet. It would be very helpful if you could provide me the html part of the datagrid using this function.
Thanks.
June 20th, 2007 at 1:07 am
Hi,
Yeah i do hit a roadblock in inserting this scripts for datagrid in DotNet, i was initially using this scripts
function select_deselectAll(chkValue, AutoNoVal)
{
var RowsSelected = 0;
var RowsAvailable = 0;
var frm = document.forms[0];
for(var i=0; ifor checking all/uncheck all, places on top of datagrid; ChkDelete=>subsequent selectable checkbox for multiple delete), compared to Dustin 1 checkbox only. I try to mimic Dustin codes by inserting the RowsSelected and RowsAvailable to calculate the TotalOn=RowsSelected, TotalBox=RowsAvailable so I can run the last if syntax but I face the problem of checkin and unchecking DeleteAll checkbox… Can someone help me bout this.. and preferably the solution comes in ASP.NET flavors
July 3rd, 2007 at 8:51 am
Perfect - Work beautifully
August 8th, 2007 at 9:23 am
just a quickie - will the js work if ur using php to display ur checkboxes in a big loop and each checkbox has the name checkbox[uniqueNUmberHereLinksToObjectsId] == unique number i..e checkbox17, checkbox21, checkbox23.. please ..
August 26th, 2007 at 8:11 pm
Hello,
is there any way by which we can toggle box check box selection script in javascript.
August 26th, 2007 at 9:37 pm
Wondered if anyone else encountered this problem… I’m on a shared server, and I put the switchSetting(this,”checkboxName[]“) and the checkAll(”checkboxName[]“);
into this one file, and both FF and IE7 pop up errors saying the script is churning too slow or continuing to run it could result make the browser/whole computer unstable.
Code: calling the various functions:
These are within a form that actually processes a script because it needs to)
(not as how it is documented with no call to any resulting file)
Ship Now Delaythen embedded in the php code: (it loops through all records, only displays what meets the requirements)
php code.
Putting the button, above or below results in the same error.
It seems to work for everyone else here, but not for me… Not sure why. Not sure if there are other “pieces” i need to insert, either above or below..
External file is pointing in the right directory… so, I’m stumped…
In the meantime, I’ll have to keep looking, but hope someone is able to shine a light on my situation.
thanks.
April 21st, 2008 at 8:58 am
I know this is quite an old post, so you probably already know this, but you should look up the PHP function “implode”. You can replace:
for ( $i=0; $i < $postCount; $i++ ) {
$deleteIds .= $_POST['del'][$i].’,';
}
$deleteIds = rtrim($deleteIds,’,');
with:
$deleteIds = implode(", ", $_POST['del']);
… or just drop it straight into the query.
Great script by the way. Very useful.
May 12th, 2008 at 4:12 pm
how we can implement something like this function in to Invisionboard Checkall Functions.
function goDel()
{
var recslen = document.forms[0].length;
var checkboxes=""
for(i=1;i<recslen;i )
{
if(document.forms[0].elements[i].checked==true)
checkboxes = " " document.forms[0].elements[i].name
}
if(checkboxes.length>0)
{
var con=confirm("Are you sure you want to delete");
if(con)
{
document.forms[0].action="delete.php?recsno=" checkboxes
document.forms[0].submit()
}
}
else
{
alert("No record is selected.")
}
}
July 24th, 2008 at 1:25 am
This is a completed code I was seeking. Thanks a lot.