473,799 Members | 3,178 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Check All Check Boxes

pw
Hi, I need to create a function in javascript to check or uncheck all
checkboxes in a form. From what I understand, I can do this either by
specifying the name of the check box fields such as:

function checkAll(list)
{
var o = document.getEle mentById(list);
var c = o.checked;
var f = document.forms. f;
var a = f.item(list);
for (var i = 0; i < a.length; i++)
a[i].checked = c;
}
or I can do this by looping through all of the fields in the form and
determining whether they are check boxes such as:

function selectAll(){
var frm = document.forms. f;

for (var i = 0; i < frm.length; i++)
if (frm.elements[i].type == 'checkbox')
frm.elements[i].checked = true;

}

My problem is that the Java code that I am stuck using generates a
unique name for each check box field. It generates the name of the
field in the format 'wire[X].wireAS' where [X] is a number that
increments sequentially based upon the number of fields in the form.

I can't use the second method, looping through all elements in the form
because it takes too long. A test page has 150 check boxes on it and
for each check box there are 8-9 hidden fields. Using IE 6 it takes
about 7 seconds to loop through each field and determine if it is a
check box. (Firefox takes <1 second).

Anyone have any ideas how I can solve this problem?

Thanks in advance.

Jul 23 '05 #1
8 2483
pw wrote:
[snip]

or I can do this by looping through all of the fields in the form and
determining whether they are check boxes such as:

function selectAll(){
var frm = document.forms. f;

for (var i = 0; i < frm.length; i++)
if (frm.elements[i].type == 'checkbox')
frm.elements[i].checked = true;

}


function selectAll(){
var frm = document.forms. f,i=frm.length; ;
while(i--){
if (frm.elements[i].type == 'checkbox'){
frm.elements[i].checked = true;
}
}
}

Your loop constantly calculates the form length, and the while loop has
been shown to be more efficient.

Mick
Jul 23 '05 #2
pw
Thanks, the while loop is much more efficient. It decreased the time
from 7 seconds to 3 seconds in IE6. Any ideas how it can be made even
faster? Unfortunately 3 seconds still feels awfully long for our users.

Jul 23 '05 #3
pw wrote:
Thanks, the while loop is much more efficient. It decreased the time
from 7 seconds to 3 seconds in IE6. Any ideas how it can be made even
faster? Unfortunately 3 seconds still feels awfully long for our users.

I tried it with 500 checkboxes.

Safari: ~1.5 secs
FF: ~2 secs
Moz: ~1.75 secs

You maybe able to stuff the cbox object references into an arrray
onload, but I doubt that would speed things up.
Mick

Jul 23 '05 #4
In article <11************ **********@o13g 2000cwo.googleg roups.com>,
pr********@gmai l.com enlightened us with...

for (var i = 0; i < frm.length; i++)
Oops.
frm.elements.le ngth

Hence, the discrepancies between MSIE and FF.

Anyone have any ideas how I can solve this problem?


Try changing that and see if it helps.
If not, can you edit the Java code generating this?

--
--
~kaeli~
Contrary to popular opinion, the plural of 'anecdote' is
not 'fact'.
http://www.ipwebdesign.net/wildAtHeart
http://www.ipwebdesign.net/kaelisSpace

Jul 23 '05 #5
pw wrote:
Thanks, the while loop is much more efficient. It decreased the time
from 7 seconds to 3 seconds in IE6. Any ideas how it can be made even
faster? Unfortunately 3 seconds still feels awfully long for our users.


I believe do..while loops are faster, try the following (generates 500
checkboxes, each with 10 hidden inputs for a total of 5,000 elements).
IE churns through it in less than 0.2 seconds, Firefox in about 1.7
seconds.

I also tried it using createElement to generate the input as I had a
feeling that generating the inputs using innerHTML helped IE to run
faster - but it made it run quicker. I've kept the innerHTML method
as IE takes nearly 30 seconds to generate the form elements using
createElement (Firefox takes about 3 seconds with innerHTML or
createElement).
<script type="text/javascript">

// This just generates the form and elements
function genInputs(d){
var j, i=500;
var t=['<form name="X" action="">'];
while (i--) {
t.push('<input name="x',
i,
'" type="checkbox" size="10">Input ',
i,
'<br>');
j = 9;
while (j--) {
t.push('<input type="hidden" value="h',
i,
'-',
j,
'">');
}
}
document.getEle mentById(d).inn erHTML = t.join('');
}

function checkAll(f){
f = f.elements;
alert('There are ' + f.length + ' elements');
var i = 0;
var startTime = new Date();
if (f[i]){
do {
if ( 'checkbox' == f[i].type )
f[i].checked = true;
} while (f[++i])
}
var endTime = new Date();
alert('That took about ' + (endTime-startTime) + ' ms.');
}

window.onload = function() {genInputs('Y') };

</script>

<input type="button" value="click me" onclick="
checkAll(docume nt.forms['X']);
">
<div id="Y"></div>
--
Rob
Jul 23 '05 #6
JRS: In article <PN************ ******@twister. nyroc.rr.com>, dated Tue,
24 May 2005 18:56:47, seen in news:comp.lang. javascript, Mick White
<mw***********@ rochester.rr.co m> posted :
while(i--){
if (frm.elements[i].type == 'checkbox'){
frm.elements[i].checked = true;
}
}

This may be a little better, since it may reduce indexing :-

while (i--) { fi = frm.elements[i]
if (fi.type == 'checkbox') fi.checked = true
}

Result depend on what proportion of elements are checkboxes.

I have no particular reason to suppose that using an overall
var C = 'checkbox' then if (fi.type == C) ... would be better,
but it can be tried.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #7
I combined all approaches in this thread:
http://www.mattkruse.com/temp/cb_speed.html

By combining RobG's code with John's reference speedup, the speed difference
is dramatic, at least in IE.

--
Matt Kruse
http://www.JavascriptToolbox.com
Jul 23 '05 #8
"Matt Kruse" <ne********@mat tkruse.com> writes:
I combined all approaches in this thread:
http://www.mattkruse.com/temp/cb_speed.html

By combining RobG's code with John's reference speedup, the speed difference
is dramatic, at least in IE.


In Opera 8, the speedup is not so impressive. I get 64ms for the typical
version and 47ms for the RobG and RobG+John versions.

For some weird reason, both Mick White's and John Stockton's speedup
versions are 450+ms. It seems there is some optimization for accessing
sequentially in the forward direction - or rather, a serious
performance hit for doing it backwards. My guess is that lookup is
linear, but optimized for finding the value just after the previous
lookup.
In some versions there is an "if" with a "do/while" loop inside, bith
with almost the same condition. That could be changed to a single while loop,
e.g.:
---
function test5() {
var f = document.forms[0].elements;
var i = 0;
var fi;
var startTime = new Date();
while (fi=f[i++]){
if ( 'checkbox' == fi.type )
fi.checked = true;
}
var endTime = new Date();
alert('That took about ' + (endTime-startTime) + ' ms.');
}
---
No big difference in speed though :)

An even more hacked version of the loop is:

for(;(fi=f[i++])&&('checkbox'! =fi.type || (fi.checked=tru e)););

.... but as far as I can see it is exactly as fast as the above, so
no power in obfuscation here :).

/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 23 '05 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
3607
by: Mohammed Mazid | last post by:
Hi folks! Can anyone please help me with this? I am developing a Quiz program but I am stuck with "multiple answers". Basically I need some sort of code that would select multiple answers using check boxes. For example, a question such as
2
2439
by: Edward | last post by:
The following html / javascript code produces a simple form with check boxes. There is also a checkbox that 'checks all' form checkboxes hotmail style: <html> <head> <title></title> </head> <body> <form name="myform" action=test.php method=post>
2
5268
by: Ben | last post by:
My current project requires me to create part of a form that is created on the fly. The project consists a list of entries to an event. The name and address and such is easy. The design is detup so that the creater of the even can make their own event in the database. When they do so a 2 tables are created. One for the entries such as names and the other is for the parameters of each event. The creator then goes in and makes each event...
0
1968
by: Robert | last post by:
Stephen, I think I figured out the problem. I was able to get Check Boxes and Option Buttons to work on my form by TURNING OFF RECORD SELECTORS on the form. Not sure why this would make a difference. Perhaps Access attributes the hWnd of the form to the Record Selector if these are turned on. In any case, I ran some tests on your Customers form and sure enough, a Check Box or Option Button will work fine until you turn on Record...
11
11972
by: Darryl Kerkeslager | last post by:
I wanted to test for only one True value in a bunch of checkboxes, so I figured I could just test for a value of exactly -1 after adding the values. In case 0 below, it worked. But in all other cases, it failed, with a Type error. Come to find out, sometimes, for no *apparent* reason - "True" is returned, at other times, -1. Can someone explain this (seemingly) random behavior, and tell me a way to force the integer result?...
2
1916
by: muthu | last post by:
Hi freinds, In my aspx page i have generated some check boxes dynamically using dhtml. When i check any check box and submit the form,how can i capture the value of check box. How should i identify wich check box is been checked.And the check boxes are not server controls.They are the ordinary html check boxes.Can any one help me out
2
1743
by: cpptutor2000 | last post by:
Could some PHP guru please help me? I have very standard PHP - MySQL application that reads in some data from a table and for each row, puts a check box at the start of the row. Now the check boxes are variable in number, depending only on the number of current records in the database table. My question is: how do I count the number of check boxes rendered at any one time. I tried having a global variable and incrementing it each time a...
1
1626
by: Java Kumar | last post by:
Hi Friends, I have a form which contains elements such as check boxes,text box,text area ., Problem is in Check boxes. By default, Check boxes are unchecked and text boxes are blank. I clicked one check box and entered some values in text boxes. then After a page refresh, the values of text boxes are cleared.But the check box is appears with check mark. the default value (unchecked) is not restored... Why ? How can i...
4
1516
by: wish | last post by:
Dear all; I have a lot of check boxes in the page..if the the user keep check the check boxes rather then check one check box for all check boxes will checked.. May i have ur help to refer? Thanks.
2
1927
by: KMEscherich | last post by:
Microsoft Access 2003 Hi there, am stuck with something that I am not sure on how to get done. I am attempting to have 3 check boxes and have 3 date fields. I need to have each date field be populated with an independent date when the end-user clicks on each of the 3 check boxes. CB_STARTED STARTED_DATE CB_COMPLETED COMPLETED_DATE
0
9686
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10475
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10250
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10222
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
10026
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9068
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
5463
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4139
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3757
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.