The problem that led to this snippet of code was that when posting from a form to a PHP script, you may sometimes want to have several fields with the same name and different values. For example, you might want people to be able to tick boxes to indicate which cities they have been to from a list. You would normally add "[]" to the name of the field inputs, like so:
<input type="checkbox" name="cities[]" value="London"> London
<input type="checkbox" name="cities[]" value="Paris"> Paris
<input type="checkbox" name="cities[]" value="Berlin"> Berlin
<input type="checkbox" name="cities[]" value="Madrid"> Madrid
<input type="checkbox" name="cities[]" value="Rome"> Rome
When the form is received by PHP, whichever items are ticked in the cities list above are accessible in the array $_POST['cities']. This is very handy.
Unfortunately, the addition of square brackets causes trouble with JavaScript, especially with a "Select All" function - which allows you to check all boxes at once by clicking a single one. This script works around that using regular expressions.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Checkbox Fun</title>
<script type="text/javascript"><!--
var formblock;
var forminputs;
function prepare() {
formblock= document.getElementById('form_id');
forminputs = formblock.getElementsByTagName('input');
}
function select_all(name, value) {
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 (value == '1') {
forminputs[i].checked = true;
} else {
forminputs[i].checked = false;
}
}
}
}
if (window.addEventListener) {
window.addEventListener("load", prepare, false);
} else if (window.attachEvent) {
window.attachEvent("onload", prepare)
} else if (document.getElementById) {
window.onload = prepare;
}
//--></script>
</head>
<body>
<form id="form_id" name="myform" method="get" action="search.php">
<a href="#" onClick="select_all('area', '1');">Check All Fruit</a> | <a href="#" onClick="select_all('area', '0');">Uncheck All
Fruit</a><br><br>
<input type="checkbox" name="area[]" value="1" />Apples<br />
<input type="checkbox" name="area[]" value="2" />Bananas<br />
<input type="checkbox" name="area[]" value="3" />Chickens<br />
<input type="checkbox" name="area[]" value="4" />Stoats
<br><br><a href="#" onClick="select_all('location', '1');">Check All Locations</a> | <a href="#" onClick="select_all('location',
'0');">Uncheck All Locations</a><br><br>
<input type="checkbox" name="location[]" value="1" />Brighton<br />
<input type="checkbox" name="location[]" value="2" />Hove<br />
</form>
</body>
</html>
55 Comments
Nice code.
Thanks!
#1, JRD, United States, 28 August 2005. Reply to this.
thx a lot! nice and clear code :)
#2, sylvio, France, 5 September 2005. Reply to this.
But Mr. it does not work in Mozilla ...
#3, Majid, United Arab Emirates, 13 September 2005. Reply to this.
thanks a lot ... working well with firefox.
#4, deltanine, Germany, 13 September 2005. Reply to this.
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)
Replies: #50 and #53.
#5, Rafael, Poland, 20 September 2005. Reply to this.
Great work guys,
both work great on Firefox. This was causing me dramas but all is now well. :)
#6, Scott, New Zealand, 6 October 2005. Reply to this.
am, it doesnt work in firefox for me... could you help me guys... thanks
#7, Jortworx, Philippines, 24 October 2005. Reply to this.
thanks... just what i needed
#8, timmygrimm, United States, 3 November 2005. Reply to this.
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
#9, imran, United Kingdom, 4 November 2005. Reply to this.
Works fine in IE6, but not in Firefox.
I tried the idea in #5 but it didnt work at all.
#10, Zac Craven, United Kingdom, 10 November 2005. Reply to this.
Doesn't work with Firefox 1.0.7
Works fine in IE...
#11, Eddie, Taiwan, 25 November 2005. Reply to this.
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
#12, Anthony Eskinazi, United Kingdom, 10 December 2005. Reply to this.
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!
#13, Sergej Brin, Malta, 18 December 2005. Reply to this.
Thanks, saved me a bunch of time. Post-solution works fine in firefox and IE. #5 didnt seem to work in firefox...
#14, J.D., Canada, 10 January 2006. Reply to this.
Thanks - just what I needed!
#15, Mac, Unknown, 31 January 2006. Reply to this.
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');" />
#16, Richard, United Kingdom, 6 March 2006. Reply to this.
"#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?
#17, Patricia, El Salvador, 13 March 2006. Reply to this.
Exactly what I was looking for, gracias!
#18, Casey, United States, 6 April 2006. Reply to this.
I've looked hard for this. Hope it works. Thanks.
#19, Colin, United States, 8 April 2006. Reply to this.
If works for me on Firefox 1.5 and IE 6.
It's exactly what I was looking for.
Thanks
#20, Will, France, 13 April 2006. Reply to this.
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!!!
#21, deste, Italy, 22 May 2006. Reply to this.
Thanks! I had this very issue and your solution saved me some time! Thanks again!
#22, Anonymous, Canada, 8 June 2006. Reply to this.
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)"
#23, Kasso isse, Finland, 12 June 2006. Reply to this.
Thanks a lot! Just what I was looking for.
#24, Ian Hart, United Kingdom, 13 June 2006. Reply to this.
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
#25, Net Developpeur, France, 17 July 2006. Reply to this.
Thanks for the Firefox/IE compatibility fix, Kasso.
Everyelse else, please note: the Jack Daniels code does not work on Firefox!
#26, Jonas, United States, 19 July 2006. Reply to this.
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?!
#27, patrad, Unknown, 16 August 2006. Reply to this.
nevermind, I had to change the DOM casue it was the second form on the page.
#28, patrad, United States, 16 August 2006. Reply to this.
nice, that was just what i needed right now.
many thanks, you saved the day!
#29, aleks, Germany, 22 August 2006. Reply to this.
Excellent work around. It worked perfectly. Thanks Alot.
#30, Freakshow, United States, 29 August 2006. Reply to this.
Thanks very much - that helped me out loads!
#31, NA, United Kingdom, 5 September 2006. Reply to this.
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.
#32, Arnod, Canada, 6 September 2006. Reply to this.
THANKS GUYS! Saved me a few hours of work ;)
#33, Devin, United States, 17 September 2006. Reply to this.
Just what I was hoping to find! Nice example!
#34, Travis, United States, 28 September 2006. Reply to this.
Sorry for your time.... Why i can't see images on this resource?
My Browser is: Opera.
Thank you.
#35, Green_Monkey23, United States, 4 October 2006. Reply to this.
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.
#36, Dave Child, United Kingdom, 4 October 2006. Reply to this.
hello ladies and gents!
I've been kind of lurking around.
I love this site! thanks for having me :)
#37, Nanbe1st, Unknown, 13 October 2006. Reply to this.
Nice! Just what I was looking for. Works with firefox and IE.
#38, Atul Felix, India, 24 October 2006. Reply to this.
Thanks! Just what we needed for the app we are building.
#39, Bryan, Unknown, 3 November 2006. Reply to this.
thks ..the code helped me as well..
#40, Anonymous, United States, 9 November 2006. Reply to this.
exactly what i was looking for...
thanks a lot!
#41, AS, Germany, Unknown, 22 November 2006. Reply to this.
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;
}
}
}
#42, Tim Henderson, United States, 11 December 2006. Reply to this.
Bravo, bravo, bravo
#43, pardalsalcap, Spain, 18 December 2006. Reply to this.
It works fine
thanks a lot!
#44, Sanjib, India, 28 December 2006. Reply to this.
Thanks for your code
#45, Vinod Ram, India, 9 December 2009. Reply to this.
mighty fine code, chef thanks alot
#46, robin verschoren, gelbium, 5 July 2010. Reply to this.
good job man!!!!!!
thanx....
#47, hiren, india, 27 July 2010. Reply to this.
Been looking for this solution for a long time. Had one that worked in Firefox but not IE.
This is slick and works with both.
THANKS
DenS
#48, DenS, USA, 19 October 2010. Reply to this.
Thank you for this article! This saved a lot of time from me, I was having exactly this same problem :)
#49, JanneK, Finland, 24 October 2010. Reply to this.
solution #5 is great and working for all IE and FF.. thks a lot.
#50, Anonymous, MALAYSIA, 15 December 2010. Reply to this.
var count=0;
<input type= inputbox id = "hi " name="hello<%=count%>" value='Y'>
<%= count++%>
i have 10 input boxes and the name for them are iterated in loop like above code.
now i want to fetch the value of each input box like
for(i=0;i<10:i++) {
var xxx = document.mainform.hello[i].value;
}
but its not working bcoz its taking name as hello and might be searching for its i'th position. can some one help how to get the value of the input box.
i am coding this in Jsp..
i tried with
document.getElementById('hi'+i).value also still throwing error its not an object
#51, anmol, India, 12 March 2011. Reply to this.
typo sorry its
<input type= "text" id = "hi " name="hello<%=count%>" value='Y'>
#52, anmol, India, 12 March 2011. Reply to this.
#5 didnt work in firefox 4 for me, the following does
function checkAll(field, value) {
for (var i=0;i<document.getElementById("advancedSearchForm").elements[field].length;i++) {
if(value == 1) {
document.getElementById("advancedSearchForm").elements[field][i].checked = true
} else {
document.getElementById("advancedSearchForm").elements[field][i].checked = false
}
}
}
#53, bhosty, 9 May 2011. Reply to this.
You can add a common class to check box and easily using jQuery each.
<input type="checkbox" name="id[]" value="2" checked="checked" class="cb">
// check all
$(".frmcb").each(function()
{
this.checked = true;
});
#54, shabeer, UAE, 1 June 2011. Reply to this.
Thanks for the nice code, it works.
great piece of work
#55, Mohsin, Pakistan, 17 February 2012. Reply to this.