tags:

views:

97

answers:

2

Hi Everyone

I have a form validation function that loops through the form elements checking for empty fields - code below:

function formValidate(ourform){
  var formelems = document.getElementById(ourform).elements;

  for (var i=0; i<formelems.length; i++){
  if(formelems[i].value == "") {
   alert("Empty Field(s). Please fill in all the fields.");
   return false;
    }   
  }    
}

the problem is that my form does not return false if there's an empty field - it processes the form. I have solved this before but now i just cannot remember how.

Thanks.

A: 

Hai try this,

function checkForEmpties(form) {
var i;
var formElements = form.elements;


for (i=0; i<formElements.length; i++) 
    {
 if (formElements[i].type == "text") {
  if (formElements[i].value != "") {
   return true;
   break;
  }
 }
 else if (formElements[i].type == "checkbox") {
  if (formElements[i].checked) {
   return true;
   break;
  }
 } 

}
return false;
    }
Pandiya Chendur
Why the `break`s?
Victor
+1  A: 

Basically the answer is that in your example, you aren't actually returning anything. In Pandiya's example he is returning true/false depending on the conditions. Remember to also use a return statement in whatever even call you are using, probably in your example it would be

<form blah blah blah onsubmit="return formValidate(this)">
jon
How dumb of me, i forgot to add the 'return' part in my form. Thanks Jon.
Q_the_dreadlocked_ninja
no problem man, I've done that stuff so many times. stare at a piece of code for too long and you're unable to look at it with fresh eyes. you going to mark the answer?
jon
already done that.
Q_the_dreadlocked_ninja