Javascript

Associate
Joined
13 Nov 2004
Posts
207
Location
Newcastle upon Tyne
I have written the following block of code, which cycles through each element on a form, stopping to alert individually, which fields contain 0 characters or a null value.

Code:
for(var i = 0; i < form.elements.length; i++){
		if(form.elements[i].value.length == 0 || form.elements[i].value == "null"){
			alert('No value entered in '+form.elements[i].name+' field.');
			form.elements[i].focus();
			return false; //form has errors halt submit to server
		}
	}return true; //all fields are completed appropriately
How can I amend this to record the details for each field missing data and display one alert box at the end with each error on a new line?

Hope this makes sense.

I had a go, but could only get the first error message into the array I created.
 
Last edited:
Try this:

Code:
var message = "No value entered in the following field(s):";

for (var i = 0; i < form.elements.length; i++) {
	if (!form.elements[i].value.length || !form.elements[i].value) {
		message += "\n"+form.elements[i].name;
	}
}

alert(message);

You loose the focus ability but you can now record all of the empty fields and generate one message. I also shortened your if statement since the ==0 and =="null" are equivilent to "false".
 
Last edited:
I did test the code I wrote and it worked with the field name being displayed.

You shouldn't need to access the field names outside the loop, the loop adds the field name to a new line (\n) in the message varable which was declared outside the loop. The alert then displays the message variable.

If your still having problems, post the code up and I'll have a look.
 
Ahhhhhhh

I over looked the "\n". My apoloigies.

I have rewritten the code now and approached from a different angle.

Code:
/*** do any of the fields have no data or null values ***/
		if (!(form.elements[i].value.length) || (form.elements[i].value == "null")){
			noDataCount++; /* count number of fields with no data entered */
			form.elements[i].className = "input-boxError"; /* highlight data missing */
		}

if(noDataCount > 0){ /* data missing from at least one field */
		
		_errorMessage = "No details entered in the "+noDataCount+" highlighted field(s)";
		errorOnPage(form, _errorMessage); /* write error to message to page */
		return false; /* halt form submission */
	
	}else{ 
			return dataVal(form) /* begin validation on field data specifics */
		}

/*
	*** function to write error specific message to errorDetail area of page.
	*/
	function errorOnPage(form, _errorMessage){
		
		var pageElement; /* used for form error alert message */
		
		/* Find errorDetail element on page and update with error warning.  NOTE:  replaces invisible &nbsp; value set on initial page load */
		pageElement = document.getElementById("errorDetail");
		pageElement.lastChild.nodeValue = _errorMessage; /* write specific error message passed by calling function */
	}
 
Back
Top Bottom