views:

136

answers:

3

I have a form that lists users, and for each user there is a drop down menu (2 choices: waiting, finished) and a comments textbox. The drop down menus are each labeled "status-userid" and the comments textbox is labeled "comments-userid" ... so for user 92, the fields in his row are labeled status-92 and comments-92.

I need to validate the form in the following way: If the value of the status is "finished", I have to make sure that the user entered comments to correspond with that specific drop down menu.

So far, I have:

/* code */

function validate_form () {
valid = true; 

    /*here's where i need to loop through all form elements */
    if ( document.demerits.status-92.value == "finished" &&   
         document.demerits.comments-92.value == "")
    {
            alert ( "Comments are required!" );
            valid = false;
    }

    return valid;
}

How do I loop through all of the status-userid elements in the form array?! Or is there another way to do this? Thanks for your help!

A: 

You'll need a collection of the dropdowns in your form. This can be acquired by using getElementsByTagName.

var dropdowns = document.demerits.getElementsByTagName("select");

for (var i = 0; i < dropdowns.length; i++)
{
    // You can now reference the individual dropdown with dropdowns[i]
}
Joel Potter
You would need a second array for inputs (which you hopefully are all textboxes). It'll work but its a bit fragile.
AnthonyWJones
Aye. You're method is better. ;-)
Joel Potter
A: 

I believe my answer here (and in even more detail here) will help you.

Peter Bailey
+2  A: 

This should do it in raw Javascript (no framework).

var form = document.demerits;

for (var i = 1; i <= 100; i++)
{
  if (form["status-" + i.toString()].value == "finished" &&
      form["comments-" + i.toString()].value == "")
  {
      // enable visibility of element next to comments indicating validation problem
      valid = false;
  }
}

Using alerts would be bad though.

AnthonyWJones