2

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:

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?

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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]
}

2 Comments

You would need a second array for inputs (which you hopefully are all textboxes). It'll work but its a bit fragile.
Aye. You're method is better. ;-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.