Schoolboy error?

~J~

~J~

Soldato
Joined
20 Oct 2003
Posts
7,558
Location
London
I'm doing something OBVIOUSLY wrong here, but for the life of me can't see what it is!

function validateForm() {
if (isEmpty(document.forms[0].txtName.value) == true)
{
alert("Please Tell us your name.");
document.forms[0].txtName.focus();
return (false);
}

<input id="txtName" type="text" name="txtName" />
<input id="Submit" type="button" value="submit" onclick="validateForm();" />

Won't bore you with the rest, the <input> tags are in a <form>, but just getting an "Object Expected" error when it hits the JavaScript!
 
You're missing a trailing brace and IsEmpty isn't a native JS function. If you don't want to include a whole other script just for checking if a value is or isn't there you could change your code to:

Code:
function validateForm() {
	var elForm = document.forms[0]
	if (elForm.txtName.value.replace(/\S/g, "")=="") {
		alert("Please tell us your name.");
		elForm.txtName.focus();
		return (false);
	} 
}
 
I'd personally use a form name rather than just catching it with the array or use a this object.

Problem with your script is that if at any point you add another form on that page you will have to change everything about.

function validateForm(form) {
if (parseInt(form.txtName.value) != form.txtName.value) {
alert('Please tell us your name');
form.txtName.focus();
form.txtName.select();
return false;
}


<input id="Submit" type="button" value="submit" onclick="validateForm(this);" />
 
Cheers Spunkey, trailing brace is actually there (my fault, sorry, didn't paste it), but honestly didn't know about the isEmpty not native!!

Will change accordingly!

Nathan: Yeah agree 100%, but it's only ever one form, just a dead easy capture page.
 
I'd personally use a form name rather than just catching it with the array or use a this object.
I agree completely, however the name property of the FORM element has been deprecated and causes a warning when validating IIRC.

Adding another form to the page shouldn't be too much of a headache. If it's after the current form, no problem. If it's before, the line I added means it's just a change of the array index in one place to get the correct form.
 
Back
Top Bottom