Validating Radio Buttons in JavaScript

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

    Validating Radio Buttons in JavaScript

    I am attempting to validate radio buttons in Netscape with JavaScript.

    Everything works excellent in Explorer, but refuses to work in Netscape
    (all versions).


    =========== JAVASCRIPT CODE =============== =========

    function ValidateTest()
    {
    var q1 = false;
    var q2 = false;

    for (counter = 0; counter < TEST.Q1.length; counter++)
    {
    if (TEST.Q1[counter].checked)
    q1 = true;
    }
    for (counter = 0; counter < TEST.Q2.length; counter++)
    {
    if (TEST.Q2[counter].checked)
    q2 = true;
    }

    if (!q1)
    {
    alert("Please select an answer for Question #1.");
    return false;
    }
    else if (!q2)
    {
    alert("Please select an answer for Question #2.");
    return false;
    }

    document.TEST.s ubmit();
    }

    =========== HTML FORM CODE =============== ==========

    <form name="TEST" method="post" action="evaluat ion-e.cfm">
    <ol>
    <li>Question 1?<br>
    <input type="radio" name="Q1" value="1">1<br>
    <input type="radio" name="Q1" value="2">2<br>
    <input type="radio" name="Q1" value="3">3<br>
    <input type="radio" name="Q1" value="4">4<br>
    <input type="radio" name="Q1" value="5">5<br> <br>
    </li>
    <li>Question 2?
    <br><input type="radio" name="Q2" value="1">1<br>
    <input type="radio" name="Q2" value="2">2<br>
    <input type="radio" name="Q2" value="3">3<br>
    <input type="radio" name="Q2" value="4">4<br>
    <input type="radio" name="Q2" value="5">5<br> <br>
    </li>
    </ol>
    <input type="button" value="Continue " onClick="Valida teTest()">
    </form>

    =============== =============== =============== =======

    The JavaScript error that I receive is the following:

    "TEST is not defined."

    =============== =============== =============== =======

    TEST is the name of my form. Is there any quick fix that I can do to
    the code above to make it work in Netscape?

    Sincerely,

    Marc

  • Rob B

    #2
    Re: Validating Radio Buttons in JavaScript



    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dt d">
    <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
    <head>
    <title>feh!</title>
    <script type="text/javascript">
    //<![CDATA[

    function isChecked(radgr p)
    {
    var i = radgrp.length;
    do
    if (radgrp[--i].checked)
    return true;
    while (i);
    return false;
    }

    function validateTest(el s)
    {
    var focus_me = null, msg = "";
    if (!isChecked(els .Q1))
    {
    msg += "• Question #1\n";
    focus_me = focus_me || els.Q1[0];
    }
    if (!isChecked(els .Q2))
    {
    msg += "• Question #2\n";
    focus_me = focus_me || els.Q2[0];
    }
    if (msg != "")
    {
    var prefix = "\nThe following Question(s) were not answered:\n\n";
    var suffix = "\nPlease correct and re-submit. Thank you.\n";
    alert(prefix + msg + suffix);
    if (focus_me)
    focus_me.focus( );
    return false;
    }
    return true;
    }

    //]]>
    </script>
    </head>
    <body>
    <form name="TEST" method="post" action="evaluat ion-e.cfm"
    onsubmit="retur n validateTest(th is.elements)">
    <ol>
    <li>Question 1?<br>
    <input type="radio" name="Q1" value="1">1<br>
    <input type="radio" name="Q1" value="2">2<br>
    <input type="radio" name="Q1" value="3">3<br>
    <input type="radio" name="Q1" value="4">4<br>
    <input type="radio" name="Q1" value="5">5<br> <br>
    </li>
    <li>Question 2?
    <br><input type="radio" name="Q2" value="1">1<br>
    <input type="radio" name="Q2" value="2">2<br>
    <input type="radio" name="Q2" value="3">3<br>
    <input type="radio" name="Q2" value="4">4<br>
    <input type="radio" name="Q2" value="5">5<br> <br>
    </li>
    </ol>
    <input type="submit" value="Continue ">
    </form>
    </body>
    </html>

    *** Sent via Developersdex http://www.developersdex.com ***
    Don't just participate in USENET...get rewarded for it!

    Comment

    • Michael Winter

      #3
      Re: Validating Radio Buttons in JavaScript

      On 7 Dec 2004 10:26:47 -0800, sakms <marc.marclalon de@pwgsc.gc.ca> wrote:

      [snip]
      [color=blue]
      > Everything works excellent in Explorer, but refuses to work in Netscape
      > (all versions).[/color]

      IE allows the name or id of an element to be a reference to that element.
      Frankly its nonsense and most browsers treat it as an error. The correct
      way to refer to the form is

      document.forms['form-name-or-id']

      or

      document.forms[n]

      where n is a number representing the 'n'th form in the document.

      However, there's a simpler way if you modify how the function is called.

      var questions = 2;

      function validate(form) {var element;
      for(var i = 1, j, n; i <= questions; ++i) {
      /* Obtain a reference to the ith question. */
      element = form.elements['Q' + i];
      j = 0; n = element.length;

      /* At the end of this loop, j will hold
      * the index of the selected value.
      */
      while((j < n) && element[j].checked) {++j;}

      /* If no item is selected, j will
      * equal the number of items.
      */
      if(j == n) {
      alert('Please select an answer for question ' + i);
      return false;
      }
      }
      return true;
      }

      and call it with

      <form ... onsubmit="retur n validate(this); ">

      This way, you don't even need to name the form[1].

      [snip]
      [color=blue]
      > <form name="TEST" method="post" action="evaluat ion-e.cfm">
      > <ol>
      > <li>Question 1?<br>
      > <input type="radio" name="Q1" value="1">1<br>
      > <input type="radio" name="Q1" value="2">2<br>
      > <input type="radio" name="Q1" value="3">3<br>
      > <input type="radio" name="Q1" value="4">4<br>
      > <input type="radio" name="Q1" value="5">5<br> <br>[/color]

      This should *really* be a nested list:

      <ol>
      <li>Blah blah blah?
      <ol>
      <li><label><inp ut type="radio" name="Q1" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q1" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q1" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q1" value="...">
      Blah</label></li>
      </ol>
      </li>
      <li>Blah blah blah?
      <ol>
      <li><label><inp ut type="radio" name="Q2" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q2" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q2" value="...">
      Blah</label></li>
      <li><label><inp ut type="radio" name="Q2" value="...">
      Blah</label></li>
      </ol>
      </li>
      </ol>

      and styled with

      ol {
      list-style-type: decimal;
      margin: 1em 0 0 2em;
      padding: 0;
      }
      ol ol {
      list-style-type: lower-alpha;
      margin: 0 0 1em 1em;
      }

      Or, if you're not interested in having inner numbering, change the nested
      lists to UL elements, and the second rule to:

      ol ul {
      list-style-type: none;
      margin: 0 0 1em 0;
      }

      [snip]

      Hope that helps,
      Mike


      [1] And you shouldn't: forms should be identified using the id attribute
      unless you're supporting an old browser like NN4 which doesn't support ids.

      --
      Michael Winter
      Replace ".invalid" with ".uk" to reply by e-mail.

      Comment

      • Rob B

        #4
        Re: Validating Radio Buttons in JavaScript

        Michael Winter wrote:

        (snip)
        [color=blue]
        > /* At the end of this loop, j will hold
        > * the index of the selected value.
        > */
        > while((j < n) && element[j].checked) {++j;}[/color]
        [color=blue]
        > /* If no item is selected, j will
        > * equal the number of items.
        > */[/color]

        (snip)

        Mike:

        while((j < n) && !element[j].checked) {++j;}

        like mine better, tho ;)

        *** Sent via Developersdex http://www.developersdex.com ***
        Don't just participate in USENET...get rewarded for it!

        Comment

        • Michael Winter

          #5
          Re: Validating Radio Buttons in JavaScript

          On Tue, 07 Dec 2004 19:34:02 GMT, Rob B <ferndoc9@hotma il.com> wrote:

          [snip]
          [color=blue]
          > Mike:
          >
          > while((j < n) && !element[j].checked) {++j;}
          >
          > like mine better, tho ;)[/color]

          But it has the overhead of a function call. :P

          An alternative way of writing it would be:

          function isChecked(group ) {
          var i = group.length;
          while(i--) {if(group[i].checked) {return true;}}
          return false;
          }

          which avoids the 'do'.

          By the way, you didn't alter the mark-up to conform to XHTML rules. All
          those BR and INPUT elements should end />. Well, the BR elements shouldn't
          be there at all as I said in my post, but if they must, they should be <br
          />. :)

          Mike

          --
          Michael Winter
          Replace ".invalid" with ".uk" to reply by e-mail.

          Comment

          • Dr John Stockton

            #6
            Re: Validating Radio Buttons in JavaScript

            JRS: In article <1102444006.980 177.166850@f14g 2000cwb.googleg roups.com>
            , dated Tue, 7 Dec 2004 10:26:47, seen in news:comp.lang. javascript,
            sakms <marc.marclalon de@pwgsc.gc.ca> posted :
            [color=blue]
            >I am attempting to validate radio buttons in Netscape with JavaScript.[/color]

            Another approach would be to add a new member to every set of buttons,
            default checked; put all of them at the bottom marked "Office Use Only",
            and test on submit that each is now clear.

            --
            © 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

            • RobG

              #7
              Re: Validating Radio Buttons in JavaScript

              Dr John Stockton wrote:
              [...][color=blue]
              > Another approach would be to add a new member to every set of buttons,
              > default checked; put all of them at the bottom marked "Office Use Only",
              > and test on submit that each is now clear.[/color]

              And if they had style="display: none;" they can't be clicked on, saving
              user confusion and defeating attempts by contrary questioners to select
              them for the sole purpose of annoying the examiner...

              --
              Rob

              Comment

              Working...