Check All Check Boxes

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • pw

    #1

    Check All Check Boxes

    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.

  • Mick White

    #2
    Re: Check All Check Boxes

    pw wrote:
    [snip][color=blue]
    >
    > 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;
    >
    > }
    >[/color]

    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

    Comment

    • pw

      #3
      Re: Check All Check Boxes

      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.

      Comment

      • Mick White

        #4
        Re: Check All Check Boxes

        pw wrote:
        [color=blue]
        > 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.
        >[/color]
        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

        Comment

        • kaeli

          #5
          Re: Check All Check Boxes

          In article <1116953151.232 366.318720@o13g 2000cwo.googleg roups.com>,
          preswright@gmai l.com enlightened us with...[color=blue]
          >
          > for (var i = 0; i < frm.length; i++)[/color]

          Oops.
          frm.elements.le ngth

          Hence, the discrepancies between MSIE and FF.
          [color=blue]
          >
          > Anyone have any ideas how I can solve this problem?[/color]

          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'.



          Comment

          • RobG

            #6
            Re: Check All Check Boxes

            pw wrote:[color=blue]
            > 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.
            >[/color]

            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

            Comment

            • Dr John Stockton

              #7
              Re: Check All Check Boxes

              JRS: In article <PNKke.18036$tM 3.5973@twister. nyroc.rr.com>, dated Tue,
              24 May 2005 18:56:47, seen in news:comp.lang. javascript, Mick White
              <mwhite13BOGUS@ rochester.rr.co m> posted :
              [color=blue]
              > while(i--){
              > if (frm.elements[i].type == 'checkbox'){
              > frm.elements[i].checked = true;
              > }
              > }[/color]


              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.

              Comment

              • Matt Kruse

                #8
                Re: Check All Check Boxes

                I combined all approaches in this thread:


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

                --
                Matt Kruse



                Comment

                • Lasse Reichstein Nielsen

                  #9
                  Re: Check All Check Boxes

                  "Matt Kruse" <newsgroups@mat tkruse.com> writes:
                  [color=blue]
                  > 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.[/color]

                  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 - lrn@hotpop.com
                  DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
                  'Faith without judgement merely degrades the spirit divine.'

                  Comment

                  Working...