views:

113

answers:

2

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

+1  A: 
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!');
  }
}
stefita
A: 

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]);
    }
  }
}
CMS