Looping through form elements

D

DoomedLung

Hey,

I'm in the process of writing a function to check each element of a
form isn't empty. I've come to a dead end..

Here is my function:


function validateData(){

var i;

var form = document.forms[0];

var formElem = form.elements;

for(i = 0; i < formElem.length; i++){

if(formElem.value == ""){

alert('you have not fill out the form');
break;

}else if(formElem.value != ""){

continue;

}

formElem.focus();

}

}

Any help would be much appreciated :)
 
D

DoomedLung

sorry this is the my amended function that needs scrutinised:

function validateData(){
var i;
var form = document.forms[0];
var formElem = form.elements;
for(i = 0; i < formElem.length; i++){
if(formElem.value == ""){
alert('you have not fill out the form');
break;
}else if(formElem.value != ""){
continue;
}
}
formElem.focus();
}

:)
 
L

Lee

DoomedLung said:
sorry this is the my amended function that needs scrutinised:

function validateData(){
var i;
var form = document.forms[0];
var formElem = form.elements;
for(i = 0; i < formElem.length; i++){
if(formElem.value == ""){
alert('you have not fill out the form');
break;
}else if(formElem.value != ""){
continue;
}
}
formElem.focus();
}


You don't need the else clause. The loop is going to continue
if the first condition doesn't trigger the break.
If you did need the else clause, you wouldn't need to specify
the condition. Simply:
else {
continue;
}

would be equivalent. You never need to test the positive and
negative cases of a condition. One or the other must be true.

The problem is that if it loops through all of your elements
and doesn't find any problems, it's still going to execute
the last line "formElem.focus()", and at that point, the
index "i" is one more than the last element in the form.

You only want to set focus if there is a problem.
The easiest way to do that is to move that last line up to
just before the break.


--
 
D

DoomedLung

I removed else clause and moved up the focus() just before the loop
breaks and now it works!

Thank you for the advice :)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top