Javascript accessing an array of checkboxes

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

    Javascript accessing an array of checkboxes

    In my HTML, I have several of the following:

    <input type='checkbox' name='right[]' id='right[]' value='0' />

    All are the same except the value is set differently for each one. The
    reason for the [] is so I can access the checkbox values as an array on
    the processing page (when clicking 'Submit');

    However, I want my Javascript code to examine these objects first. My
    onclick event handler function (below) is called (I get the 'hi there'
    popup), but it does nothing afterward (i.e., neither 'checkbox' alert
    appears, and the handler, strangely, seems to return 'true').

    I suppose my problem is that I am not specifying the checkbox array
    properly. I tried several variations, but I've been working on this
    problem alone for several hours and am getting nowhere. Can someone show
    me the correct syntax to do this, please. (My form name and id are set
    to 'appl'...)

    <script lang='JavaScrip t'>
    function verifyAllChecke d()
    {
    alert('hi there');
    if(document.app l.right[0].checked == true) {
    alert('checkbox is checked');
    } else {
    alert('checkbox is not checked');
    }
    return false;
    }
    </script>
  • RobG

    #2
    Re: Javascript accessing an array of checkboxes

    Rainman wrote:[color=blue]
    > In my HTML, I have several of the following:
    >
    > <input type='checkbox' name='right[]' id='right[]' value='0' />
    >
    > All are the same except the value is set differently for each one. The
    > reason for the [] is so I can access the checkbox values as an array on
    > the processing page (when clicking 'Submit');
    >
    > However, I want my Javascript code to examine these objects first. My
    > onclick event handler function (below) is called (I get the 'hi there'
    > popup), but it does nothing afterward (i.e., neither 'checkbox' alert
    > appears, and the handler, strangely, seems to return 'true').
    >
    > I suppose my problem is that I am not specifying the checkbox array
    > properly. I tried several variations, but I've been working on this
    > problem alone for several hours and am getting nowhere. Can someone show
    > me the correct syntax to do this, please. (My form name and id are set
    > to 'appl'...)
    >
    > <script lang='JavaScrip t'>[/color]

    The script element does not have a 'lang' attribute, though there is a
    deprecated 'language' attribute. Just use the required type attribute:

    <script type="text/javascript">
    [color=blue]
    > function verifyAllChecke d()
    > {
    > alert('hi there');
    > if(document.app l.right[0].checked == true) {[/color]

    if(document.app l.elements['right[]'].checked) {

    or

    if(document.for ms['appl'].elements['right[]'].checked) {


    Read "My element is named myselect[] , how do I access it?" in th FAQ:

    <URL:http://www.jibbering.c om/faq/#FAQ4_25>


    [...]


    --
    Rob

    Comment

    • Rainman

      #3
      Re: Javascript accessing an array of checkboxes

      > if(document.app l.elements['right[]'].checked) {

      Excellent response... very helpful, especially the link you provided.
      What worked for me is:

      if(document.app l.elements['right[]',0].checked) {

      Mark

      Comment

      • RobG

        #4
        Re: Javascript accessing an array of checkboxes

        Rainman wrote:[color=blue][color=green]
        >> if(document.app l.elements['right[]'].checked) {[/color]
        >
        >
        > Excellent response... very helpful, especially the link you provided.
        > What worked for me is:
        >
        > if(document.app l.elements['right[]',0].checked) {[/color]

        That appears to be using a little-used feature of the HTMLCollections
        interface[1]. If there is only one checkbox with that name, then:

        if(document.app l.elements['right[]'].checked) {


        will do the trick. However, if there is more than one checkbox with a
        name of 'right[]' then:

        document.appl.e lements['right[]']


        will return a collection, and since a collection doesn't have a checked
        property, attempting to evaluate it returns 'undefined'.

        Your method specifies an item number in the parameters to get the first
        checkbox with that name:

        document.appl.e lements['right[]', 0].checked


        The more common method is:

        document.appl.e lements['right[]'][0].checked


        The advantage of your method is that it will return a reference to the
        first right[] checkbox even if there is only one, whereas the other
        method will cause an error if there is only one.

        Did you stumble across it or read it in a reference somewhere? I would
        not have deduced that behaviour from the spec, though both IE and
        Firefox are consistent so I guess it's written clearly enough for
        someone to understand.


        1. <URL:http://www.w3.org/TR/DOM-Level-2-HTML/html.html#ID-75708506>



        --
        Rob

        Comment

        • Lasse Reichstein Nielsen

          #5
          Re: Javascript accessing an array of checkboxes

          Rainman <name@yourdomai n.com> writes:
          [color=blue][color=green]
          >> if(document.app l.elements['right[]'].checked) {[/color]
          >
          > Excellent response... very helpful, especially the link you
          > provided. What worked for me is:
          >
          > if(document.app l.elements['right[]',0].checked) {[/color]

          Quite by conicidence, though.

          There is only one expression allowed inside a "square-bracket"
          property accessor. You attempt to provide two, with a comma between
          them, as if it was a method call with two arguments. That is not
          what happens. This is correct syntax at all because of a little known
          and used feature of Javascript (inherited from C along with much other
          syntax baggage): a comma separated sequence of expressions is itself
          an expression, and its value is the value of the last of the expressions.

          In this case, your expression is equivalent to:
          document.appl.e lements[0].checked
          This works as desired only if the first element named "right[]" is
          also the first form control in the form at all.

          More correct would be:
          document.appl.e lements['right[]'][0].checked
          which takes merely the first element named "right[]", while assuming
          that there are more than one.

          /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

          • Thomas 'PointedEars' Lahn

            #6
            Re: Javascript accessing an array of checkboxes

            Lasse Reichstein Nielsen wrote:
            [color=blue]
            > More correct would be:
            > document.appl.e lements['right[]'][0].checked
            > which takes merely the first element named "right[]", while assuming
            > that there are more than one.[/color]

            And even more correct, being the standards compliant approach, would be

            document.forms['appl'].elements['right[]'][0].checked

            However, it appears that the method this piece of code is part of is for
            common form data verification. Therefore:

            <meta http-equiv="Content-Script-Type" content="text/javascript">
            ...
            <script type="text/javascript">
            function verifyAllChecke d(f)
            {
            var result = false;

            alert('hi there');

            var o;
            if (f && f.elements && (o = f.elements['right[]']))
            {
            // the OP probably wants a for-loop here
            if (o[0].checked)
            {
            alert('checkbox is checked');
            result = true;
            }
            else
            {
            alert('checkbox is not checked');
            }

            return result;
            }
            ...
            <form ... onsubmit="retur n verifyAllChecke d(this);">
            ...
            </form>

            In that case, the form's name would not matter anymore.


            PointedEars

            Comment

            • RobG

              #7
              Re: Javascript accessing an array of checkboxes

              Lasse Reichstein Nielsen wrote:[color=blue]
              > Rainman <name@yourdomai n.com> writes:
              >
              >[color=green][color=darkred]
              >>> if(document.app l.elements['right[]'].checked) {[/color]
              >>
              >>Excellent response... very helpful, especially the link you
              >>provided. What worked for me is:
              >>
              >>if(document.a ppl.elements['right[]',0].checked) {[/color]
              >
              >
              > Quite by conicidence, though.
              >
              > There is only one expression allowed inside a "square-bracket"
              > property accessor. You attempt to provide two, with a comma between
              > them, as if it was a method call with two arguments. That is not
              > what happens. This is correct syntax at all because of a little known
              > and used feature of Javascript (inherited from C along with much other
              > syntax baggage): a comma separated sequence of expressions is itself
              > an expression, and its value is the value of the last of the expressions.
              >
              > In this case, your expression is equivalent to:
              > document.appl.e lements[0].checked
              > This works as desired only if the first element named "right[]" is
              > also the first form control in the form at all.[/color]

              Thank you for clarifying that!

              When calling a method surplus arguments are ignored (or in some languages
              all stuffed into the last parameter). I expected expression property
              accessors work the same way - nice to know why they don't.

              [...]



              --
              Rob

              Comment

              • RobG

                #8
                Re: Javascript accessing an array of checkboxes

                Thomas 'PointedEars' Lahn wrote:[color=blue]
                > Lasse Reichstein Nielsen wrote:
                >
                >[color=green]
                >>More correct would be:
                >> document.appl.e lements['right[]'][0].checked
                >>which takes merely the first element named "right[]", while assuming
                >>that there are more than one.[/color]
                >
                >
                > And even more correct, being the standards compliant approach, would be
                >
                > document.forms['appl'].elements['right[]'][0].checked
                >
                > However, it appears that the method this piece of code is part of is for
                > common form data verification. Therefore:
                >
                > <meta http-equiv="Content-Script-Type" content="text/javascript">
                > ...
                > <script type="text/javascript">
                > function verifyAllChecke d(f)
                > {
                > var result = false;
                >
                > alert('hi there');
                >
                > var o;
                > if (f && f.elements && (o = f.elements['right[]']))
                > {
                > // the OP probably wants a for-loop here
                > if (o[0].checked)[/color]


                Wouldn't it be better here to see if o is a collection or not, then
                optionally do a loop? Something like:


                var oneChecked = false;

                if (o){
                if (o.length) {
                for (var i=0, len=o.length; i<len && !oneChecked; ++i){
                oneChecked = o[i].checked ;
                }
                } else {
                oneChecked = o.checked;
                }
                alert('At least one right[] checked? ' + ((oneChecked)?' Yes':'No'));
                }



                [...]


                --
                Rob

                Comment

                • Rainman

                  #9
                  Re: Javascript accessing an array of checkboxes

                  Whoa!! Way more info than I was counting on! Thanks, though, as it is
                  all helpful. The notation:

                  document.appl.e lements['right[]',0].checked

                  works for this, but it failed for the array of <textarea>s. What you
                  pointed out, namely the syntax of:

                  document.appl.e lements['right[]'][0].checked

                  works correctly for both. I got the former syntax indirectly from RobG,
                  whose original reply to my post gave a link:

                  <URL:http://www.jibbering.c om/faq/#FAQ4_25>

                  which had 3 more links for more information. The top one (I think) of
                  those had the format of the former.

                  Mark

                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Javascript accessing an array of checkboxes

                    RobG wrote:
                    [color=blue]
                    > Thomas 'PointedEars' Lahn wrote:[color=green]
                    >> [...] it appears that the method this piece of code is part of is for
                    >> common form data verification. Therefore:
                    >>
                    >> <meta http-equiv="Content-Script-Type" content="text/javascript">
                    >> ...
                    >> <script type="text/javascript">
                    >> function verifyAllChecke d(f)
                    >> {
                    >> var result = false;
                    >>
                    >> alert('hi there');
                    >>
                    >> var o;
                    >> if (f && f.elements && (o = f.elements['right[]']))
                    >> {
                    >> // the OP probably wants a for-loop here
                    >> if (o[0].checked)[/color]
                    >
                    > Wouldn't it be better here to see if o is a collection or not, then
                    > optionally do a loop?[/color]

                    It would definitely.
                    [color=blue]
                    > Something like:
                    >
                    > var oneChecked = false;
                    >
                    > if (o){
                    > if (o.length) {[/color]

                    However, I am unsure as to whether this would suffice. There could be an
                    undocumented proprietary `length' property of the element object and this
                    method would fail then. What about this:

                    if (o.length && typeof o[0] == "object" && o[0])
                    {
                    [color=blue]
                    > for (var i=0, len=o.length; i<len && !oneChecked; ++i){
                    > oneChecked = o[i].checked ;
                    > }
                    > } else {
                    > oneChecked = o.checked;
                    > }
                    > alert('At least one right[] checked? ' + ((oneChecked)?' Yes':'No'));
                    > }[/color]

                    I would exchange the two operands of the continue-condition of the `for'
                    statement, though; if we detect that at least one checkbox was checked,
                    it does not matter anymore if this was the last one or not.

                    Apart from that, well done.


                    PointedEars

                    Comment

                    Working...