Categories:

Home / Free JavaScripts / Forms / Here

Cut & Paste Check required elements

Credit: JavaScript Kit

Description: This is an easy-to-setup form validation script that allows you to specify certain form elements as "required". When the surfer submits the form, the script checks these elements to make sure that are NOT empty before allowing the form submission to proceed. Before, this work was usually handled by a CGI script; this is a JavaScript that essentially performs the same task.

Note: This script uses features of JavaScript 1.1, which is only supported by NS 3+ and IE 4+. All other browsers will simply not participate in the form validation.

Example: Below is a sample form. Try filling out different elements, and submitting it. All "required" elements have to be filled before submission is allowed.

Sample form: (* required elements)

Name: *
Email: *
Hobbies: *
Comments:

Directions

Step 1: Insert the below into the <head> section of your page:

Step 2: Add the following inside the <form> tag of the form you wish to validate:

<form onSubmit="return checkrequired(this)">
--
--
</form>

Specifying required elements: Now, to mark an element inside the form as "required", simply prefix the element's name with the keyword "required". Uh? For example, using the above example, the source code looks something like this:

<form onSubmit="return checkrequired(this)">

<input type="text" name="requiredname">
<input type="text" name="requiredemail">
<select name="requiredhobby">
<option>....</option>
</select>
<textarea name="comments"></textarea>

</form>

Notice how the names of all of the required elements have one thing in common- their names have the prefix "required". This indicates to the script that those are elements that have to have input in them. For either text or textarea elements, this means they have to contain some text; for selection list, this means at least one selection has to be selected.

Note: Due to the "optional" nature of check and radio boxes, this script cannot be used to mark those elements as required (giving check or radio boxes a "required" prefix will do nothing).


JavaScript Tools:
Site Info

CopyRight 1998-2014 JavaScript Kit. NO PART may be reproduced without author's permission.