Check if a Form Element Exists Using JavaScript

July 19th, 2012 - Posted by Steve Marks to Javascript / jQuery, Web Development.

In my day-to-day work I get involved with hundreds of forms. Some of these forms are similar, differing only very slightly with the addition of the odd textbox, but all require some sort of validation.

Rather than have a separate JavaScript function for each scenario, it’s sometimes easier to simply check if a field exists before interacting with it.

Lets take a look at the simple form below containing two text inputs:

<form name="form1" onsubmit="return validateMe();">
	Field 1: <input type="text" name="field1" value="" /><br />
	Field 2: <input type="text" name="field2" value="" /><br />
	<input type="submit" name="Submit" value="Submit" />
</form>

And now lets use a similar form, but that only has one text input:

<form name="form1" onsubmit="return validateMe();">
	Field 1: <input type="text" name="field1" value="" /><br />
	<input type="submit" name="Submit" value="Submit" />
</form>

In order to use the same function to validate both forms we can use the following JavaScript:

function validateMe()
{
	if (document.form1.field1.value == "")
	{
		alert("Please complete Field 1");
		return false;
	}
	
	if (typeof document.form1.field2 != "undefined" && document.form1.field2.value == "")
	{
		alert("Please complete Field 2");
		return false;
	}
	
	return true;
}

Notice that for the second field we’re checking to make sure it is not undefined before checking for it’s value. Without this, the function would result in a JavaScript error and the form would be submitted regardless of the return from the function.

This entry was posted on Thursday, July 19th, 2012 at 8:17 am by +Steve Marks and is filed under Javascript / jQuery, Web Development. You can follow any responses to this entry through the RSS 2.0 feed.
Comments...

Fear not, we won't publish this

Comments (4)
  1. Your absolutely right. In that case you’d want to give each element an ID and instead of document.form1.field1.value do document.getElementById(‘my_field_id’).value

  2. Bhavna says:

    This method is not suitable to validate elements while using loop.

  3. Amudhan says:

    Good work.

  4. Heli13 says:

    Thanks it works fine for me