Re: form validation assistance (Javascript)

by "Steve Mount" <steve(at)saltyrain.com>

 Date:  Tue, 16 Apr 2002 15:11:07 -0400
 To:  "Michael Gerholdt" <Michael.Gerholdt(at)fredonia.edu>,
<hwg-techniques(at)hwg.org>
 References:  fredonia
  todo: View Thread, Original
You can't just build the object name the way you are.  You're close, though.
Here's how I'd do it:

var checklist;
var i, j, checked;

for (i=1;i<=22;i++) {
  checklist = eval("document.Evaluation.o" + i);
  checked = 0;
  for (j=0; j<checklist.length; j++) {
    if (checklist[j].checked) {
      checked = 1;
      break;
    }
  }
  if (!checked) {
    alert("Check something, will ya?");
    event.returnValue=false;
    checklist[0].focus();
    return false;
  }
}

The "checked" variable could be eliminated... I'd also get rid of the use of
the event object, but whatever.

I wrote a quick test page to show this in action.  To see it, go here:

http://www.saltyrain.com/stuff/checktest.html

Note in my example, I cut it down to just three lines of radio buttons, so I
adjusted my for loop accordingly.

-------------------------------------------------------------
Steve Mount, Software Engineer            steve(at)saltyrain.com
Home Site                            http://www.saltyrain.com
US Constitution Online          http://www.usconstitution.net

----- Original Message -----
From: "Michael Gerholdt" <gerholdt(at)fredonia.edu>
To: <hwg-techniques(at)hwg.org>
Sent: Tuesday, April 16, 2002 10:52 AM
Subject: form validation assistance (Javascript)


> Hi,
>
> We have a form with various elements but most are radio buttons with
exactly
> the same number of buttons and values - 22 of them.
>
> I got validation to work for them with 22 if-blocks but want to reduce
this
> to one.
>
> We're using form-level validation with the onSubmit event.
>
> Here's the block I've been working with. If I take out the part that does
> the actual validation, the for loop works fine as indicated by the alert.
> But apparently I'm missing something on how to pass the value into the if
> statement.
>
> btw, we named the radio buttons o1 through o22. (Javascript doesn't like
> elements named with numbers alone? This is a nice workaround.)
>
> Appreciate any help!
>
> Thanks,
> Mike
>
> for (i=1;i<=22;i++) {
> var NUM = i;
> NUM = 'o' + NUM;
> alert(NUM);
> if (!(Evaluation.NUM[0].checked || Evaluation.NUM[1].checked ||
> Evaluation.NUM[2].checked || Evaluation.NUM[3].checked ||
> Evaluation.NUM[4].checked)) {
> alert('Check something, will ya?.');
> event.returnValue=false;
> document.Evaluation.NUM[0].focus();
> return false;
> }
> }
>
>

HWG hwg-techniques mailing list archives, maintained by Webmasters @ IWA

This page is part of a preserved archive of archives.hwg.org. The site is no longer active and its content is not maintained. For enquiries about this archive, write to archive(at)iwanet.org.