Skip Navigation

"Select All" JavaScript for Forms Posting to an Array

This may be useful to someone - a question on the BNM list led to this small piece of JavaScript.

The original problem was that when posting to a PHP script, in order to have the result as an array (when using a set of checkboxes for example), the quickest way to do this is to add "[]" to the item name (eg 'name="area[]"). Then, PHP can access $_POST['area'] as an array in the receiving script.

Unfortunately, the addition of square brackets causes trouble with JavaScript, especially with a "Select All" function. This script works around that using regular expressions, and might prove useful to someone experiencing the same problem later.

  1. <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  2. <html>
  3. <head>
  4. <title>Checkbox Fun</title>
  5. <script type="text/javascript"><!--
  6. var formblock;
  7. var forminputs;
  8. function prepare() {
  9. formblock= document.getElementById('form_id');
  10. forminputs = formblock.getElementsByTagName('input');
  11. }
  12. function select_all(name, value) {
  13. for (i = 0; i < forminputs.length; i++) {
  14. // regex here to check name attribute
  15. var regex = new RegExp(name, "i");
  16. if (regex.test(forminputs[i].getAttribute('name'))) {
  17. if (value == '1') {
  18. forminputs[i].checked = true;
  19. } else {
  20. forminputs[i].checked = false;
  21. }
  22. }
  23. }
  24. }
  25. if (window.addEventListener) {
  26. window.addEventListener("load", prepare, false);
  27. } else if (window.attachEvent) {
  28. window.attachEvent("onload", prepare)
  29. } else if (document.getElementById) {
  30. window.onload = prepare;
  31. }
  32. //--></script>
  33. </head>
  34. <body>
  35. <form id="form_id" name="myform" method="get" action="search.php">
  36. <a href="#" onClick="select_all('area', '1');">Check All Fruit</a> | <a href="#" onClick="select_all('area', '0');">Uncheck All
  37. Fruit</a><br><br>
  38. <input type="checkbox" name="area[]" value="1" />Apples<br />
  39. <input type="checkbox" name="area[]" value="2" />Bananas<br />
  40. <input type="checkbox" name="area[]" value="3" />Chickens<br />
  41. <input type="checkbox" name="area[]" value="4" />Stoats
  42. <br><br><a href="#" onClick="select_all('location', '1');">Check All Locations</a> | <a href="#" onClick="select_all('location',
  43. '0');">Uncheck All Locations</a><br><br>
  44. <input type="checkbox" name="location[]" value="1" />Brighton<br />
  45. <input type="checkbox" name="location[]" value="2" />Hove<br />
  46. </form>
  47. </body>
  48. </html>

44 comments

JRD
United States #1: August 28, 2005
Nice code.
Thanks!
sylvio
France #2: September 5, 2005
thx a lot! nice and clear code :)
Majid
United Arab Emirates #3: September 13, 2005
But Mr. it does not work in Mozilla ...
thanks a lot ... working well with firefox.
Rafael
Poland #5: September 20, 2005
I think, it can be done much easier, without using RegExp object.
Just use the elements property of a HTMLFormElement
http://www.w3.org/TR/2000/WD-DOM-Level-2-HTML-20001113/html.html#ID-1689064

function select_all(name,value){
for(var t, i=0;t=formblock.elements[name][i++];t.checked=value);
}

and then set the onclick attribute to:
onclick="select_all('area[],1)"
or
onclick="select_all('area[]',0)
(the formblock variable is the reference to the form)
Great work guys,

both work great on Firefox. This was causing me dramas but all is now well. :)
Jortworx
Philippines #7: October 24, 2005
am, it doesnt work in firefox for me... could you help me guys... thanks
timmygrimm
United States #8: November 3, 2005
thanks... just what i needed
 United Kingdom #9: November 4, 2005
Hi

I did like your blog postings and comments but i have soem problem if some1 could help me out.

Does anyone know how to pass html table data from parent to a child form html table ? Or may be you could let me know any URL related to this topic.

Any kind of help is highly appericiated.

Thanks

Imran Hashmi
http://www.visionstudio.co.uk
Zac Craven
United Kingdom #10: November 10, 2005
Works fine in IE6, but not in Firefox.

I tried the idea in #5 but it didnt work at all.
Doesn't work with Firefox 1.0.7
Works fine in IE...
works great in IE but not in Firefox, please can you either post here how to mkae it work in FOrefox or e-mail me at support@unicentral.co.uk

Thank you
Sergej Brin
Malta #13: December 18, 2005
Very good site! I like it! I just wanted to pass on a note to let you know what a great job you have done with this site..Thanks!
Thanks, saved me a bunch of time. Post-solution works fine in firefox and IE. #5 didnt seem to work in firefox...
Thanks - just what I needed!
Richard
United Kingdom #16: March 6, 2006
A great piece of code!

I modified it a little so that I have my list of checkboxes with an extra checkbox at the end labelled "select all", which when clicked checked checks all the other check boxes and when de-checked unchecks them all:
CODE=========================
var selectedAll = "false";
function select_all(name)
{
for (i = 0; i < forminputs.length; i++)
{
// regex here to check name attribute
var regex = new RegExp(name, "i");
if (regex.test(forminputs[i].getAttribute('name')))
{
if(selectedAll == "false")
{
forminputs[i].checked = true;
}
else
{
forminputs[i].checked = false;
}
}
}
if(selectedAll == "false")
{
selectedAll = "true";
}
else
{
selectedAll = "false";
}
}
CODE=========================

The input tag is then used as follows:

<input type="checkbox" onClick="checkAll('area');" />
Patricia
El Salvador #17: March 13, 2006
"#14. J.D. on January 10, 2006:
Thanks, saved me a bunch of time. Post-solution works fine in firefox and IE. #5 didnt seem to work in firefox..."
it did not work for me in FireFox i am using version 1.5 ¿Which one are you using?
Casey
United States #18: April 6, 2006
Exactly what I was looking for, gracias!
Colin
United States #19: April 8, 2006
I've looked hard for this. Hope it works. Thanks.
Will
France #20: April 13, 2006
If works for me on Firefox 1.5 and IE 6.
It's exactly what I was looking for.
Thanks
Great!
It's 2 days that I'm trying to solve a problem with php/multiple checkbox selection... My DOM-javascript must be improved... :-(
But, now, your code saves me! :-)))
Thanks a lot!!!
Anonymous
Canada #22: June 8, 2006
Thanks! I had this very issue and your solution saved me some time! Thanks again!
Kasso isse
Finland #23: June 12, 2006
Tested with Firefox / IE and works fine:

function checkAll(field, value) {
for (var i=0;i<document.forms[0].elements[field].length;i++) {
if(value == 1) {
document.forms[0].elements[field][i].checked = true
} else {
document.forms[0].elements[field][i].checked = false
}
}
}

onClick attributes for selecting / deselecting checkboxes:

onclick="checkAll('boxarray[]',1)" / onclick="checkAll('boxarray[]',0)"
Thanks a lot! Just what I was looking for.
Excellent javascript,

You save me a lot of time, your script is perfect, I was just needing a script like this one.

Thanks a lot for your nice blog and website,

Paul
Jonas
United States #26: July 19, 2006
Thanks for the Firefox/IE compatibility fix, Kasso.

Everyelse else, please note: the Jack Daniels code does not work on Firefox!
patrad
Unknown #27: August 16, 2006
tried so hard to make this work as I know it is the problem I am having, although I am getting an error with the object. document.forms.0.elements[...].length is null or not an object

help?!
patrad
United States #28: August 16, 2006
nevermind, I had to change the DOM casue it was the second form on the page.
aleks
Germany #29: August 22, 2006
nice, that was just what i needed right now.

many thanks, you saved the day!
Freakshow
United States #30: August 29, 2006
Excellent work around. It worked perfectly. Thanks Alot.
NA
United Kingdom #31: September 5, 2006
Thanks very much - that helped me out loads!
I love solution #5. Nice simple trick to get the job done. It works in IE and Firefox. I heard some users in this thread have issue with Firefox, not me. Perhap because I am using the latest. 1.5.0.6.
Devin
United States #33: September 17, 2006
THANKS GUYS! Saved me a few hours of work ;)
Travis
United States #34: September 28, 2006
Just what I was hoping to find! Nice example!
Sorry for your time.... Why i can't see images on this resource?
My Browser is: Opera.
Thank you.
Hi Green_Monkey23. I don't know - I use Opera as well. Is it just this site? It might be you have "Show Images" set to off or cached.
hello ladies and gents!
I've been kind of lurking around.
I love this site! thanks for having me :)
Atul Felix
India #38: October 24, 2006
Nice! Just what I was looking for. Works with firefox and IE.
Thanks! Just what we needed for the app we are building.
Anonymous
United States #40: November 9, 2006
thks ..the code helped me as well..
AS, Germany
Unknown #41: November 22, 2006
exactly what i was looking for...

thanks a lot!
Another method:

If you're putting IDs in the array elements like this:
<input type=checkbox name='newsel[13]' value='Y'>
<input type=checkbox name='newsel[10]' value='Y'>

Then this code will work:

//==========
// checkAll
//--------------------------------
// Check all checkboxes in a list
//================================
function checkall(form, name, value){
for (x in form) {
if (x.match(name)) {
form[x].checked=value;
}
}
}
Bravo, bravo, bravo
It works fine

thanks a lot!

Comments Disabled

Sorry, but comments are no longer being accepted on this post. This is usually because a post has become out of date, or has become the target for an unusually high quantity of comment spam.