0

So im trying to perform a basic validation to check if a field is empty. I want to do it in a loop..

<input type="text" size="25" name="q170_Name" class="text" value="" id="q170"  maxlength="100" maxsize="100" />

function validateMe() {
var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"];
var totalz = (dropdowns.length);
//loop through the array
for ( var i in dropdowns ) {
    if (document.getElementById(dropdowns[i]) == "") {
        alert('missed one!');
}}}

I appreciate the help

2 Answers 2

1
if (document.getElementById(dropdowns[i]).value == "") {
        alert('missed one!');

--edit

but probably there is a better way to do this:

for (var i = 0; i < document.myFormName.length; ++i) {
  if(  document.myFormName.elements[i].type == "text" &&
       document.myFormName.elements[i].value == "") {
     alert('missed one!');
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

I recommend you to do a simple for loop since for..in is meant to iterate over object properties, also note that you need to check the value attribute of the fields:

function validateMe() {
  var dropdowns = ["q170","q172","q173","q174","q175","q176","q177"],
      totalz = dropdowns.length,
      i;

  for (i = 0; i < totalz; i++) {
    if (document.getElementById(dropdowns[i]).value == "") {
      alert('Check the value of ' + dropdowns[i]);
    }
  }
}

Comments

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.