Get radiobox value

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

    #1

    Get radiobox value

    Hello,

    I want to check if user select one from the radiobox group. How can I get
    the radiobox actual value in javascript. In the value field I see the
    default value, but how can I know if it really was selected?

    Thanks!

    <input name="menu_orde r" id = "menu_order 1" type="radio" value="1">one<b r>
    <input name="menu_orde r" id = "menu_order 2" type="radio" value="2">two<b r>



  • Robert

    #2
    Re: Get radiobox value

    [color=blue]
    >
    > I want to check if user select one from the radiobox group.[/color]

    I'd use the term radio button group.

    Examine:

    <html>
    <head>
    <title>Radio button value</title>


    <script type="text/javascript">

    function validate()
    {
    alert("We are in function validate");
    var checkedButton;
    var allOK= false;
    var x = document.forms["myForm"];

    // Figure out which radio button was pressed

    if (x.receiveVia[0].checked == true)
    {
    checkedButton = x.receiveVia[0].value;
    allOK = true;
    }
    else if (x.receiveVia[1].checked == true)
    {
    checkedButton = x.receiveVia[1].value;
    allOK = true;
    }
    else
    {
    alert("button not pressed");
    checkedButton = '';
    allOK = false;
    }


    alert("checkedB utton = " + checkedButton +
    "; allOK = " + allOK);

    return allOK;

    }
    </script>

    </head>

    <body>

    <p>Please try out our form.</p>

    <form name="myForm"
    action="http://www.nonamedomai n.com"
    method="POST"
    onsubmit="alert ('submitting'); return validate();">

    <p><input type="radio" name="receiveVi a" value="printed" >&nbsp;Printe d
    brochure</p>
    <p><input type="radio" name="receiveVi a" value="byEmail" ">&nbsp;Via
    Email</p>

    </p>
    <p><input type="submit" value="Submit">


    </p>

    </form>

    </body>
    </html>


    Robert

    Comment

    • Grant Wagner

      #3
      Re: Get radiobox value

      Robert wrote:
      [color=blue][color=green]
      > >
      > > I want to check if user select one from the radiobox group.[/color]
      >
      > I'd use the term radio button group.
      >
      > Examine:
      >
      > <html>
      > <head>
      > <title>Radio button value</title>
      >
      > <script type="text/javascript">
      >
      > function validate()
      > {
      > alert("We are in function validate");
      > var checkedButton;
      > var allOK= false;
      > var x = document.forms["myForm"];
      >
      > // Figure out which radio button was pressed
      >
      > if (x.receiveVia[0].checked == true)
      > {
      > checkedButton = x.receiveVia[0].value;
      > allOK = true;
      > }
      > else if (x.receiveVia[1].checked == true)
      > {
      > checkedButton = x.receiveVia[1].value;
      > allOK = true;
      > }
      > else
      > {
      > alert("button not pressed");
      > checkedButton = '';
      > allOK = false;
      > }
      >
      >
      > alert("checkedB utton = " + checkedButton +
      > "; allOK = " + allOK);
      >
      > return allOK;
      >
      > }
      > </script>
      >
      > </head>
      >
      > <body>
      >
      > <p>Please try out our form.</p>
      >
      > <form name="myForm"
      > action="http://www.nonamedomai n.com"
      > method="POST"
      > onsubmit="alert ('submitting'); return validate();">
      >
      > <p><input type="radio" name="receiveVi a" value="printed" >&nbsp;Printe d
      > brochure</p>
      > <p><input type="radio" name="receiveVi a" value="byEmail" ">&nbsp;Via
      > Email</p>
      >
      > </p>
      > <p><input type="submit" value="Submit">
      >
      > </p>
      >
      > </form>
      >
      > </body>
      > </html>
      >
      > Robert[/color]

      More generic solution that works with any group of radio buttons:

      function getRadioValue(f ormName, radioInputName) {
      var f = document.forms[formName];
      if (f) {
      f = f.elements[radioInputName];
      }
      if (f) {
      if (typeof f.length == 'undefined') {
      f = [ f ];
      }
      for (var i = 0; i < f.length; i++) {
      if (f[i].checked) {
      return f[i].value;
      }
      }
      }

      return null;
      }

      function validate(f) {
      if (getRadioValue( 'myForm', 'receiveVia') == null) {
      alert("You haven't selected a \"Receive Via\".");
      return false;
      }

      return true;
      }

      --
      | Grant Wagner <gwagner@agrico reunited.com>

      * Client-side Javascript and Netscape 4 DOM Reference available at:
      *


      * Internet Explorer DOM Reference available at:
      *
      http://msdn.microsoft.com/workshop/a...ence_entry.asp

      * Netscape 6/7 DOM Reference available at:
      * http://www.mozilla.org/docs/dom/domref/
      * Tips for upgrading JavaScript for Netscape 7 / Mozilla
      * http://www.mozilla.org/docs/web-deve...upgrade_2.html


      Comment

      • Thomas 'PointedEars' Lahn

        #4
        Re: Get radiobox value

        Robert wrote:

        Who wrote that? Please provide proper attribution.
        vvvvvvvvvvvvvvv vvvvvvvvvvvvvvv vvvvvvvvvvvvvvv vvvvv[color=blue][color=green]
        >> I want to check if user select one from the radiobox group.[/color]
        >
        > I'd use the term radio button group.
        >
        > Examine:
        > [...]
        > function validate()
        > {
        > alert("We are in function validate");
        > var checkedButton;
        > var allOK= false;
        > var x = document.forms["myForm"];
        >
        > // Figure out which radio button was pressed
        >
        > if (x.receiveVia[0].checked == true)
        > {
        > checkedButton = x.receiveVia[0].value;
        > allOK = true;
        > }
        > else if (x.receiveVia[1].checked == true)
        > {
        > checkedButton = x.receiveVia[1].value;
        > allOK = true;
        > }
        > else
        > {
        > alert("button not pressed");
        > checkedButton = '';
        > allOK = false;
        > }
        >
        >
        > alert("checkedB utton = " + checkedButton +
        > "; allOK = " + allOK);
        >
        > return allOK;
        >
        > }[/color]

        That code does not scale well. Radio buttons, i.e. "input" elements
        with type="radio" of a group need to have the same name. In the DOM,
        that results in an elements collection (HTMLCollection object), thus
        the following is better:

        function getCheckedRadio (
        /** @argument HTMLFormElement */ oForm,
        /** @argument string */ sGroup)
        /**
        * @author
        * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
        * @returns
        * null, if @{(oForm)} is invalid or there is no such @{(sGroup)}<br>
        * false, if no radio button of @{(sGroup)} is checked<br>
        * A HTMLInputElemen t reference to the checked radio button otherwise
        */
        {
        var result = null, e, ig;
        if (oForm
        && (e = oForm.elements)
        && (ig = e[sGroup]))
        {
        result = false;
        for (var i = 0, len = ig.length, io = null;
        i < len;
        i++)
        {
        if ((io = ig[i]).checked)
        {
        result = io;
        break;
        }
        }
        }

        return result;
        }

        var x;
        if ((x = getCheckedRadio (document.forms[0], "receiveVia ")))
        {
        alert("checkedB utton = " + x.value);
        }
        else if (x == false)
        {
        alert("No button is checked.");
        }
        else
        {
        alert("No such form or button group.");
        }


        PointedEars

        Comment

        • Robert

          #5
          Re: Get radiobox value

          Thomas 'PointedEars' Lahn <PointedEars@nu rfuerspam.de> wrote in message news:<40B940EF. 5070100@Pointed Ears.de>...[color=blue]
          > That code does not scale well.[/color]

          True. It is as example of how to access the radio buttons. I figured
          the OP could optimize it if it was desired.

          [color=blue]
          > * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
          >[/color]

          Nice function, but you copyrighted it, so we cannot use it. How
          useful is that?

          Robert

          Comment

          • Thomas 'PointedEars' Lahn

            #6
            Re: Get radiobox value

            Robert wrote:
            [color=blue]
            > Thomas 'PointedEars' Lahn [...] wrote [...] ...[color=green]
            >> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
            >>[/color]
            >
            > Nice function, but you copyrighted it, so we cannot use it.[/color]

            Is that so? That line was simply intended to declare my authorship.
            [color=blue]
            > How useful is that?[/color]

            AIUI you can still ask me if you can use it.


            PointedEars

            Comment

            • Richard Cornford

              #7
              Re: Get radiobox value

              Thomas 'PointedEars' Lahn wrote:[color=blue]
              > Robert wrote:
              >[color=green]
              >> Thomas 'PointedEars' Lahn [...] wrote [...] ...[color=darkred]
              >>> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
              >>>[/color]
              >>
              >> Nice function, but you copyrighted it, so we cannot use it.[/color]
              >
              > Is that so? That line was simply intended to declare my authorship.[/color]
              <snip>

              It seems to me that an original work (including computer code) would
              remain the intellectual property of its creator regardless of being
              published in a public forum.

              Richard.



              Comment

              • Thomas 'PointedEars' Lahn

                #8
                Re: Get radiobox value

                Richard Cornford wrote:
                [color=blue]
                > Thomas 'PointedEars' Lahn wrote:[color=green]
                >> Robert wrote:[color=darkred]
                >>> Thomas 'PointedEars' Lahn [...] wrote [...] ...
                >>>> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
                >>>>
                >>>
                >>> Nice function, but you copyrighted it, so we cannot use it.[/color]
                >>
                >> Is that so? That line was simply intended to declare my authorship.[/color]
                > <snip>
                >
                > It seems to me that an original work (including computer code) would
                > remain the intellectual property of its creator regardless of being
                > published in a public forum.[/color]

                Sure. But what does this mean in this case?


                PointedEars

                Comment

                • Richard Cornford

                  #9
                  Re: Get radiobox value

                  Thomas 'PointedEars' Lahn wrote:[color=blue]
                  > Richard Cornford wrote:[color=green]
                  >> Thomas 'PointedEars' Lahn wrote:[color=darkred]
                  >>> Robert wrote:
                  >>>> Thomas 'PointedEars' Lahn [...] wrote [...] ...
                  >>>>> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
                  >>>>
                  >>>> Nice function, but you copyrighted it, so we cannot use it.
                  >>>
                  >>> Is that so? That line was simply intended to declare my
                  >>> authorship. <snip>[/color]
                  >>
                  >> It seems to me that an original work (including computer code) would
                  >> remain the intellectual property of its creator regardless of being
                  >> published in a public forum.[/color]
                  >
                  > Sure. But what does this mean in this case?[/color]

                  It means that an explicit assertion of copyright/authorship doesn't
                  really modify the right (or lack or right) of third parties to use that
                  code without permission from its creator. That there is no difference
                  between code posted with an explicit copyright statement and code posted
                  without one because intellectual property rights follow from the
                  creation of an original work implicitly.

                  In practice there is very little in browser scripting that is new and
                  unique. Your function is reminiscent of code associated with the FAQ;
                  differently structured, particularly in its feature detecting, but
                  essentially the same process. In principle I own the rights to that
                  (specific) code from the FAQ[1], but if someone wrote more code that did
                  essentially the same thing again, it would probably not be possible to
                  determine whether it was based on either of ours, stolen verbatim form a
                  third party, or created out of the imagination of its author without
                  direct external influence.

                  Richard.

                  [1] Or do I? I wrote that code:-

                  <URL: http://jibbering.com/faq//faq_notes/...ess.html#faBut >

                  - but I cannot tell to what extent it is original. The problem is so
                  limited, and the applicable logic so obvious, that any programmer in a
                  similar situation would write similar code.

                  The next block of code on that page is based on an Idea that I first
                  encountered in posts by Grant Wagner and so could not be clamed to be
                  original (except in the implementation details, and probably not even
                  then). I recall thinking at the time that it was obviously a good idea
                  under those circumstances, but such an obvious good idea that if I had
                  encountered that actual situation prior to that point it might have
                  occurred to me as applicable anyway.

                  While the block that follows it certainly is my invention (I recall
                  thinking through the logic of the tests) but it probably isn't actually
                  unique or original either.


                  Comment

                  • Thomas 'PointedEars' Lahn

                    #10
                    Re: Get radiobox value

                    Richard Cornford wrote:[color=blue]
                    > Thomas 'PointedEars' Lahn wrote:[color=green]
                    >> Richard Cornford wrote:[color=darkred]
                    >>> Thomas 'PointedEars' Lahn wrote:
                    >>>> Robert wrote:
                    >>>>> Thomas 'PointedEars' Lahn [...] wrote [...] ...
                    >>>>>> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
                    >>>>> Nice function, but you copyrighted it, so we cannot use it.
                    >>>>
                    >>>> Is that so? That line was simply intended to declare my
                    >>>> authorship. <snip>
                    >>>
                    >>> It seems to me that an original work (including computer code) would
                    >>> remain the intellectual property of its creator regardless of being
                    >>> published in a public forum.[/color]
                    >>
                    >> Sure. But what does this mean in this case?[/color]
                    >
                    > It means that an explicit assertion of copyright/authorship doesn't
                    > really modify the right (or lack or right) of third parties to use that
                    > code without permission from its creator.[/color]

                    Full ACK.
                    [color=blue]
                    > That there is no difference between code posted with an explicit
                    > copyright statement and code posted without one because intellectual
                    > property rights follow from the creation of an original work implicitly.[/color]

                    Apparently it is a bit more difficult than that:
                    <http://www.whatiscopyr ight.org/>

                    So AIUI there was and is nothing wrong with such a line. It merely says
                    who originally made this (or contributed to it) and thus whom (and where)
                    one can turn to for issues with it, i.e. it declares the authorship. (And
                    no, I do not have registered that code at the U.S. Copyright Office ;-))
                    [color=blue]
                    > In practice there is very little in browser scripting that is new and
                    > unique. Your function is reminiscent of code associated with the FAQ;[/color]

                    I did not know of that.
                    [color=blue]
                    > differently structured, particularly in its feature detecting, but
                    > essentially the same process.[/color]

                    True. But to make that clear: It is _not_ the *same* code which is
                    supported by the fact that the code in the FAQ is also not as efficient as
                    mine is (I use variable references wherever possible instead of looking up
                    again); so *if* there in the future would be restrictions set for the FAQ
                    code (which would seem contradictory as a FAQ is intended to be used) it
                    would not impact my rights regarding my code. It is a *different* piece
                    of work.

                    (Don't worry, once the dhtml.js library is updated with it my function will
                    soon get GPL'd as almost every code I have written anyway, so one can use
                    it *freely* as long as the authorship chain is still mentioned and you take
                    heed of the other agreements of the GNU GPL [I already have a similar, older
                    one in it but that only returns the value which turned out not to be
                    sufficient]. I strongly object to software patents.)


                    PointedEars, IANAL

                    Comment

                    • Dr John Stockton

                      #11
                      Re: Get radiobox value

                      JRS: In article <c9nfvt$64m$1$8 30fa7b3@news.de mon.co.uk>, seen in
                      news:comp.lang. javascript, Richard Cornford
                      <Richard@litote s.demon.co.uk> posted at Thu, 3 Jun 2004 16:26:52 :[color=blue]
                      >Thomas 'PointedEars' Lahn wrote:[color=green]
                      >> Robert wrote:
                      >>[color=darkred]
                      >>> Thomas 'PointedEars' Lahn [...] wrote [...] ...
                      >>>> * Copyright (C) 2004 Thomas Lahn <dhtml.js@Point edEars.de>
                      >>>>
                      >>>
                      >>> Nice function, but you copyrighted it, so we cannot use it.[/color]
                      >>
                      >> Is that so? That line was simply intended to declare my authorship.[/color]
                      ><snip>
                      >
                      >It seems to me that an original work (including computer code) would
                      >remain the intellectual property of its creator regardless of being
                      >published in a public forum.[/color]

                      That is so. The Copyright notice is really little more than a customary
                      reminder.

                      By posting here, the methods are disclosed and are available for re-use
                      in any manner. It is the form of the expression that is covered by
                      copyright.

                      Copying the code exactly for use in a Web page should normally be
                      considered fair expected practice; but copying the whole in a medium
                      designed to be read by people should not be.

                      Where there is only one reasonable way of doing something, then
                      publication does not prohibit republication.

                      The FAQ has a couple of links on Copyright; there are more at <URL:http:
                      //www.merlyn.demo n.co.uk/"misclinx.htm#C opy>.

                      IANAL.

                      --
                      © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
                      <URL:http://jibbering.com/faq/> Jim Ley's FAQ for 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

                      • Richard Cornford

                        #12
                        Re: Get radiobox value

                        Thomas 'PointedEars' Lahn wrote:[color=blue]
                        > Richard Cornford wrote:[/color]
                        <snip>[color=blue][color=green]
                        >> That there is no difference between code posted with an
                        >> explicit copyright statement and code posted without one
                        >> because intellectual property rights follow from the
                        >> creation of an original work implicitly.[/color]
                        >
                        > Apparently it is a bit more difficult than that:
                        > <http://www.whatiscopyr ight.org/>[/color]

                        Isn't that always the way? :)
                        [color=blue]
                        > So AIUI there was and is nothing wrong with such a line.[/color]

                        I don't have a problem with it. I suppose some Usenet zealots might
                        complain about the needless consumption of bandwidth.

                        <snip>[color=blue][color=green]
                        >> In practice there is very little in browser scripting that
                        >> is new and unique. Your function is reminiscent of code
                        >> associated with the FAQ;[/color]
                        >
                        > I did not know of that.
                        >[color=green]
                        >> differently structured, particularly in its feature detecting,
                        >> but essentially the same process.[/color]
                        >
                        > True. But to make that clear: It is _not_ the *same* code[/color]

                        No it is not the same code. But it is very similar code, because both
                        are derived from the logic that must be applied to the situation. The
                        underlying algorithm:-

                        1. Get the radio button collection.
                        2. Loop through the collection until a button is found
                        with a - true - checked property, or the collection
                        runs out.
                        3. Return a reference to that button if one was found.

                        - is probably the only one applicable to the problem, and it is so
                        simple that all implementations will be similar.
                        [color=blue]
                        > which is supported by the fact that the code in the
                        > FAQ is also not as efficient as mine is (I use variable
                        > references wherever possible instead of looking up
                        > again);[/color]

                        To some extent that is true. Re-resolving the - radioCollection .length -
                        property for each evaluation of the test expression is less efficient
                        than assiginig the colleciton length to a local variable as you did in:-

                        | for (var i = 0, len = ig.length, io = null;
                        | i < len;
                        | i++)
                        | {
                        ...
                        | }

                        However:-

                        for(var i = ig.length;i--;){
                        ...
                        }

                        - allows for only one resolution of the collection length property and
                        avoids the variable instantiation and assignment of the - len -
                        variable. It can be applicable in this context because there is no
                        reason to prefer to loop through the collection in ascending order over
                        descending.

                        But for ultimate performance in execution I would expect:-

                        var i = ig.length;
                        if(i--){
                        do{
                        ...
                        }while(i--);
                        }

                        - to have the edge as - do-while - is more amenable to optimisation
                        that - for - loops (even with the surrounding - if - test).

                        But I was motivated to use the less efficient loop in the FAQ because it
                        is clearer (at least for less experienced/knowledgeable programmers).

                        The second use of a local variable to avoid re-resolution of a property
                        accessor:-

                        | if ((io = ig[i]).checked)
                        | {
                        | result = io;
                        | break;
                        | }

                        - may even be counterproducti ve because it happens within the - for -
                        loop. Compared with my:-

                        # if(radioCollect ion[c].checked){
                        # checkedButton = radioCollection[c];
                        # break;
                        # }

                        Certainly your assignment of - io - to - result - is faster than my
                        assignment of - radioCollection[c] - to - checkedButton - because of the
                        additional need to resolve - c - as a property of - radioCollection -,
                        but that only happens once. While your - if - expression must be slower
                        because of the additional assignment. And that expression is evaluated
                        on every iteration of the loop.

                        The bigger the radio button collection the longer the loop and the more
                        the accumulated penalty of the additional assignment, in return for a
                        small advantage that only happens once.
                        [color=blue]
                        > so *if* there in the future would be restrictions set for
                        > the FAQ code (which would seem contradictory as a FAQ is
                        > intended to be used)[/color]

                        For the record, any code that I have contributed to the FAQ and/or the
                        notes may be used by anyone who wants to (at their own risk and without
                        warranty of any kind).

                        <snip>[color=blue]
                        > ... . I strongly object to software patents.)[/color]

                        Currently software patenting seems very silly in terms of what is
                        happening, but if someone invents (and I would insist on seeing an
                        implementation, not just a concept) something _new_ and unique, I can't
                        see why they shouldn't patent it.

                        Richard.


                        Comment

                        • Dr John Stockton

                          #13
                          Re: Get radiobox value

                          JRS: In article <c9no4m$jsk$1$8 300dec7@news.de mon.co.uk>, seen in
                          news:comp.lang. javascript, Richard Cornford
                          <Richard@litote s.demon.co.uk> posted at Thu, 3 Jun 2004 18:45:57 :
                          [color=blue]
                          > In principle I own the rights to that
                          >(specific) code from the FAQ[1],[/color]
                          [color=blue]
                          >[1] Or do I? I wrote that code:-
                          >
                          ><URL: http://jibbering.com/faq//faq_notes/...ess.html#faBut >
                          >
                          >- but I cannot tell to what extent it is original.[/color]


                          Copyright was discussed a while back in relation to the clpdmFAQ (see
                          below).

                          AFAIR, it was agreed that copyright for that newsgroup FAQ actually
                          belonged to the newsgroup, being held in trust by the current agreed
                          maintainer; and that an offer of original code for the FAQ should be
                          deemed to include donation of copyright.

                          That seems to me to be the correct policy for a newsgroup FAQ.

                          Some of the discussion was in mail, but much in News; September 2003 or
                          thereabouts, subject 'miniFAQ updates' - Google should have it.

                          --
                          © John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Delphi 3 Turnpike 4 ©
                          <URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/&c., FAQqy topics & links;
                          <URL:http://www.bancoems.co m/CompLangPascalD elphiMisc-MiniFAQ.htm> clpdmFAQ;
                          <URL:http://www.borland.com/newsgroups/guide.html> news:borland.* Guidelines

                          Comment

                          • Lasse Reichstein Nielsen

                            #14
                            Re: Get radiobox value

                            Dr John Stockton <spam@merlyn.de mon.co.uk> writes:
                            [color=blue]
                            > AFAIR, it was agreed that copyright for that newsgroup FAQ actually
                            > belonged to the newsgroup, being held in trust by the current agreed
                            > maintainer; and that an offer of original code for the FAQ should be
                            > deemed to include donation of copyright.[/color]

                            While I agree completely with the sentiment, I'm not sure it won't
                            hold up in court though. A newsgroup is not a legal entity, and cannot
                            hold a copyright, and copyright can not be expected to be donated
                            without explicit consent of the author.
                            [color=blue]
                            > That seems to me to be the correct policy for a newsgroup FAQ.[/color]

                            Absolutely, and I doubt there will be anyone complaining about the use
                            of the content of the FAQ.

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