Table of Contents
The DHTML Form files are bundled in a zip file. Click on the download link in the Form section of Zapatec web site, and follow the instructions to download the file.
Save the file (zpform.zip) to your web site root folder on your computer or server.
If you have not done so, follow the instructions to download and extract the Form files.
In your web editor (Dreamweaver, UltraEdit, etc.), open the web page where you want to place the form. Position the cursor before the ending </head> tag. Paste the following style path and script paths before the ending </head> tag:
<!-- Javascript Zapatec utilities file --> <script type="text/javascript" src="utils/zapatec.js"></script> <!-- Javascript file to support form --> <script type="text/javascript" src="zpform/src/form.js"></script> <link href="zpform/themes/lightgreen.css" rel="stylesheet" type="text/css">
The zapatec.js file, which contains the general Zapatec utilities, is located in the utils folder.
The form.js file, which is the Zapatec form file, is located in the src subfolder in the zpform folder.
If your web page containing the form is saved in the Zapatec folder, these headers work without any changes. If, however, you save your web page in another location (for example, directly under your web site root folder), you need to edit the path for these files in the script.
If you have been using a version of Zapatec Form that is older than version 2.0 and are now migrating to the current version, you need to adjust the header files.
The utils.js and transport.js files are no longer supported. To upgrade, replace the old lines:
<script src="utils/utils.js" type="text/javascript"></script> <script src="src/form.js" type="text/javascript"></script> <script src="utils/transport.js" type="text/javascript"></script>
with the following ones:
<script type="text/javascript" src="utils/zapatec.js"></script> <script type="text/javascript" src="zpform/src/form.js"></script>
The new zapatec.js file includes facilities to handle AJAX communications with the server that used to be provided by the obsolete transport.js.
Themes winxp1, winxp2, alternate2 are removed.
The easiest way to use the Zapatec Form is to add the Zapatec Data Type to the class in the input HTML element. See details on data types. For example, if the HTML input field is a phone number, you would add the class name zpFormUSPhone to the input class.
<input size="20" name="phone" type="text" class='zpFormUSPhone' />
All you have to do in your HTML page is to call Zapatec.Form.setupAll
. This sets up all the forms that have a class name beginning with "zpForm", such as "zpFormDefault", "zpFormWinXP", etc.
<script type="text/javascript"> // Run this to auto-activate all "zpForm" class forms in the document. Zapatec.Form.setupAll({}); </script>
If you just want to set up a specific form, or if you need to set specific parameters, you can do this explicitly.
<script type="text/javascript"> new Zapatec.Form({ form: 'userForm', showErrors: 'afterField', statusImgPos: 'afterField' }); </script>
Another alternative is to combine both approaches by sending parameters to setupAll
to be applied to all forms:
Zapatec.Form.setupAll({ showErrors: 'afterField', showErrorsOnSubmit: true, submitErrorFunc: testErrOutput, asyncSubmitFunc: myOnSuccess, theme: 'winxp' });
Let's extend the example to the following:
We are creating a form with 3 input fields: Name, Phone Number, Comment.
The form class zpForm specifies the Zapatec class for the form object.
Name: Specifying zpFormRequired in the input class indicates that this field is required.
Phone Number: Specifying zpFormUSPhone in the input class specifies that the input must be in a valid format for U.S. telephone numbers.
Comment: is optional and can be in any format, so no class parameter is defined.
If you copy and paste the following code into a web page, you will be able to see how the Zapatec Form object automatically validates the fields.
<form action='' name='formName' id='formId' class='zpForm' method='post'> Name:<input class='zpFormRequired' size='40' name='name' type='text' /> <br /> Phone:<input class='zpFormUSPhone' size='20' name='phone' type='text' /> <br /> Comment:<input size='30' textarea='comment' type='text' /> <br /> <input value='Submit' name='Submit' type='submit' /> <input value='Clear' name='Clear' type='reset' /> </form> <script type="text/javascript"> // Run this to auto-activate all "zpForm" class forms in the document. Zapatec.Form.setupAll({}); </script>
You can also attach the Zapatec Form object using the body onload attribute instead of inside a script tag. Make sure you call Zapatec.Form AFTER the form is created.
<body onload='Zapatec.Form.setupAll({})'>
Validation works for various form elements. You can specify what text areas, dropdown menus selections and upload fields are required. For examples, see the Different HTML Form Elements Demo.
By specifying the zpFormRequired class, the following code forces the user to select a value from the dropdown menu.
<select name="age" class="zpFormRequired"> <option value="">--select--</option> <option value="less_20"><20</option> <option value="20-40">20-40</option> <option value="40-60">40-60</option> <option value="greater_60">>60</option> </select>
Similarly, this code requires the user to enter some text in the text area.
<textarea name="resume" cols="40" rows="10" class="zpFormRequired zpFormMinLength20"></textarea>
You can also require the user to select at least one checkbox in a DIV containing checkboxes or one radio button in a DIV of radio buttons:
<label class='zpFormLabel'>input type="radio" (choose any option)</label> <div style="margin-left: 10.2em"> <input value="1" name="radio" type="radio" class="zpFormRequired" /> option 1<br /> <input value="2" name="radio" type="radio" class="zpFormRequired" /> option 2<br /> <input value="3" name="radio" type="radio" class="zpFormRequired" /> option 3<br /> </div> <br /> <label class='zpFormLabel'>input type="checkbox" (check at least one)</label> <div style="margin-left: 10.2em"> <input value="1" name="checkbox" type="checkbox" class="zpFormRequired" /> option 1<br /> <input value="2" name="checkbox" type="checkbox" class="zpFormRequired" /> option 2<br /> <input value="3" name="checkbox" type="checkbox" class="zpFormRequired" /> option 3<br /> </div>
If the form element requires the user to input a file of a certain type, you can request validation for a particular extension. For example, the following code specifies the zpFormZipArc class in the input element to indicate that the input must be a filename with a .zip extension.
<input value="" size="20" name="photo" type="file" class='zpFormZipArc' />
You can easily implement a custom validation class to validate for a different file extension, based on the code for zpFormZipArc. Just copy the code below for the zpFormZipArc class and substitute the regular expression for the file extension that you want to validate. For example, if you want to validate for a PDF file, you would change the regular expression to .pdf instead of .zip and adjust the Zapatec name, error and help messages accordingly.
Zapatec.Form.addDataType( 'zpFormZipArc', 'Zip archive', /\.zip$/, "Not a zip archive", "Upload valid zip archive", null );
Using your editing or FTP program, copy or move your web page and the entire zapatec folder to the root of your website.
Using your web browser, navigate to the web page that you created to place the Zapatec DHTML Form. Congratulations! You have set up the most basic version of the Zapatec DHTML Form! Now, you can change this highly adaptable application with the help of multiple features provided.
When you create a form, you can pass a set of parameters to control the form behavior.
<script type="text/javascript"> // Run this to auto-activate all "zpForm" class forms in the document. var myForm = new Zapatec.Form.setupAll({ statusImgPos: "beforeField", showErrors: "afterField" }); </script>
This is a reference to the form. A string parameter contains the ID of the form element. An HTMLForm parameter is interpreted as a reference to a DOM object. This option is required if you do not use Zapatec.Form.setupAll()
function.
Sets the relative position of the image that shows the status of the field validation. Possible values:
afterField - Shows validation errors AFTER the input element.
beforeField - Shows validation errors BEFORE the input element.
null - Does not display a status image.
Determines where to set focus on form unit. Possible values:
firstField - first field in the form
firstRequiredField - first required field in the form
firstIncorrectField - first invalid field in the form
null - does not put focus at all.
You can specify callback function that will be called after validation has been completed. Useful to remove old error messages produced by submitErrorFunc during previous validation attempt.
Sets the relative position of the error message in relation to invalid field. Possible values:
null - Does not show validation errors.
afterField - Shows validation errors AFTER the input element.
beforeField - Shows validation errors BEFORE the input element.
function - Specifies the function that will be used to display errors. This function receives two arguments. The first one is a reference to the field DOM element. The second one is an error message. If the second argument is undefined, then the field is valid. See "Show Errors" demo.
If true, all fields are validated when the user clicks the submitErrorFunc .
button. Any invalid fields are displayed in the alert or custom error created withIf false, the fields are not validated on submit.
Displays error message while user is typing in the field.
When true - after attempt to submit form if invalid fields were found you get the ability to iterate through them using TAB key.
If true, the user cannot submit the form, until all of the fields have been validated.
If false, it is possible to submit the form with invalid fields.
To specify the form theme, set the theme and/or themePath parameters.
The theme option is required to specify a particular theme. If the theme option is not used, the default theme is loaded by default.
Use the theme parameter to pass the name of the theme, or the absolute or relative path to the theme file, that is used to display the form. Themes are located in the themes directory. The theme name is case-insensitive.
You can also use the themePath parameter to pass the directory in which the theme file is located; it should end with slash. If the path to the theme is passed as the argument to the theme option, the themePath is not needed.
By default, themePath parameter value equals to "../themes/".
//This form uses the WinXP theme new Zapatec.Form({ form: 'WinXPForm', showErrors: 'afterField', showErrorsOnSubmit: true, theme: "WinXP" }); //This form uses the LightGreen theme new Zapatec.Form({ form: 'GreenForm', showErrors: 'afterField', showErrorsOnSubmit: true, theme: "LightGreen", themePath: "../../" });
It is possible to use forms with different themes on a single web page by specifying a theme for each form.
If true, the form is hidden, until the theme has been loaded.
You can create your own custom error function instead of the default alert.
For example, you can create a DIV container to show all field errors on submit. The id of the DIV is 'divErrs'. The errOutput class is defined by the themes.
<div id='divErrs' class="errOutput"></div>
Your custom function displays all invalid fields in the DIV. The function gets a JSON object that contains information about the fields with errors. The JSON object is defined as follows:
boolean serverSide - true if this is the server response or false if it is a validation result;
string generalError- human-readable error description;
array of field error objects - field errors.
A field error object consists of
object field - field element object
string errorMessage - human-readable error description
Here is a sample callback to submit errors:
function submit_err(errors){ var strMsg=errors.generalError for (var i = 0; i < errors.fieldErrors.length; i++){ strMsg += "<br />" + (i + 1) + ': Field ' + errors.fieldErrors[i].field.name + ' ' + errors.fieldErrors[i].errorMessage; } var outputDiv = document.getElementById("divErrs"); if(outputDiv != null){ outputDiv.innerHTML = strMsg; outputDiv.style.display = "block"; } }
Basic steps:
Create the DIV;
Create the function;
Set the appropriate configuration options.
Callbacks provide the flexibility to display error messages in a variety of ways. You can:
Display the errors at the top of the form;
Display the errors at the bottom of the form;
Display the errors at both the top and bottom of the form;.
Display a summary of the number of errors in an alert box with the details in the text.
This is the function that is called after the form has been sent to the server using the Zapatec.Transport.fetch()
and a "success" response has been received from the server. The input to this function is the array of objects passed back from the server. See callbackArgs
below.
At this point the form has been successfully submitted and you can take one or more of the following actions:
If the form is inside a Zapatec Window, you can close the window.
If the user enters records into the form repeatedly, you can clear the form, indicate the success with a message, and put the cursor (focus) in the first field, so that the user can submit another record.
Replace the form with an HTML fragment, for instance "Thank you for signing up with us."
The server response will be a valid JSON string in the following format:
boolean success
- true or false;
array of objects callbackArgs
- objects that will be passed to the asyncSubmitFunc callback; optional;
string generalError
- human-readable error description; optional;
array of strings fieldErrors
- human-readable error descriptions for each error. This is the array of hashes where "key" is the field name and "key-value" - its human readable error description; optional.
Example of invalid response:
{ "success": false, "generalError": "Registration failed", "fieldErrors": [ {"login": "This login is already busy"} ] }
See the "AJAX - Asynchronous JavaScript and XML" demo
For more information about communication with the server, see AJAX Communication.
Shows animated GIF in the specified DIV while processing asyncSubmitFunc callback. Takes in one argument, an object with the following properties:
busyContainer
string or object - element where to put animated GIF;
busyImage
string - standard image name or custom image URL; optional;
busyImageWidth
number or string - image width; optional;
busyImageHeight
number or string - image height; optional.
You can specify the name of the parameter that will be sent to the server. See "How to use the serverCallback" section for details.
You can specify custom callback function that will be called each time you clone elements of your form. Function must have 4 arguments:
original
- a reference to the original DOM element;
cloneParent
- a reference to the newly created element;
cloned
- a reference to the child element inside cloneParent
that is being cloned;
children
- an array with all cloned nodes of original
node.
This option determines whether asyncSubmitFunc is performing submission. If true, buttons will stay disabled, until the response from server is received.
buttons are to be disabled while function specified byYou can create your own debugging function to generate messages about transport communications with the server. The function should pass the message to display as a string.
Here is a sample function to display transport information:
function myDebug(message){ var debugContainer = document.getElementById("debugContainer"); // If debug container does not exist yet - create it. if(debugContainer == null){ debugContainer = document.createElement("div"); debugContainer.id = "debugContainer"; var st = debugContainer.style; st.position = "absolute"; st.top = "0"; st.right = "0"; st.width = "500px"; st.height = "100px"; st.overflow = "scroll"; st.backgroundColor = "#EEEEEE"; st.fontSize = "small"; document.body.appendChild(debugContainer); } // write debug message debugContainer.innerHTML += message.replace(/&/g, '&').replace(/</g, "<").replace(/>/g, ">").replace(/\n/g, "<br />") + "<br />"; }
Using conditionalEvents configuration option you can define on what events to check conditional fields. Possible values (can be several at a time):
focus
- when a field gets focus;
blur
- when a field loses focus;
keydown
- when some field in the form fires "keyDown" event;
keypress
- when some field in the form fires "keyPress" event;
keyup
- when some field in the form fires "keyUp" event;
valueChanged
- when the value in the field changes;
booleanValueChanged
- when checkbox/radio button field is changed.
Usually you will need to use conditionalEvents: ['booleanValueChanged'
] or conditionalEvents: ['valueChanged'
]. By default , conditional fields are checked at all form events. List all the events that you want to check on using "," as a separator.
Defines character that should be displayed as a placeholder when mask is used.
Use three letters short form of the language name as a parameter.
For details, see Localization chapter.
Optional.
Use two letters short form of the country/region name as a parameter.
For details, see Localization chapter.
Optional.
Specify the encoding used for you localization purposes.
For details, see Localization chapter.
To enforce validation of a field, add the Zapatec field type name in the input class.
For example, if the input is a US zip code, add the name zpFormUSZip as the input class.
<input value="" class='zpFormUSZip' size="10" name="zip" type="text" />
If the field is a US zip code type and required, add two classes - the zpFormUSZip and the zpFormRequired - to this input class.
<input value="" class='zpFormRequired zpFormUSZip' size="10" name="zip" type="text" />
To observe how field validation works when a user is entering data into a form, see the Basic Demo.
This table shows the data types that you can currently assign to an input field.
Zapatec Name | Type | Default error Message |
---|---|---|
zpFormRequired | required field | This field is required |
zpFormUrl | URL - web address | Invalid URL |
zpFormEmail | email address | Invalid email address |
zpFormUSPhone | USA phone number | Invalid US phone number |
zpFormInternationalPhone | international phone number | Invalid international phone number |
zpFormUSZip | USA zip code | Invalid US zip code |
zpFormDate | date | Invalid date |
zpFormInt | integer | Not an integer |
zpFormFloat | floating-point number | Not a float |
zpFormCreditCard | credit card number | Invalid credit card number |
zpFormMask | mask | Does not conform to mask |
zpFormAutoCompleteStrict | pre-defined option | No such value |
zpFormMinLength | specify the integer that will define the min number of characters to be entered | Value is too short |
zpFormMaxLength | specify the integer that will define the max number of characters to be entered | Value is too long |
You can customize error messages at the field level by substituting your own text for the standard Zapatec error message.
See the Custom Error Messages demo.
For example, the default error message for a field of type zpFormInt is "Not an integer". Perhaps, you may want the message to display something like "Please enter a whole number between 1 and 100". The following code in the fieldset overrides the standard message:
<input value="" size="23" name="only_digits" type="text" class='zpFormInt zpFormIntError="Please\ enter\ a\ whole\ number\ between\ 1\ and\ 100."' />
The slashes are necessary to preserve the spaces between the words.
You can perform similar substitutions for all the Zapatec typed error messages:
zpAutoCompleteStrictError
zpFormCreditCardError
zpFormDateError
zpFormEmailError
zpFormFloatError
zpFormIntError
zpFormInternationalPhoneError
zpFormMaskError
zpFormRequiredError
zpFormURLError
zpFormUSPhoneError
zpFormUSZipError
Another way to customize error message is to edit language file for your language.
You can make your own custom data types.
For an example that uses a custom data type for currency, see the Form Data Types demo.
Name | Regex | Error Message | Help Message |
---|---|---|---|
A Currency | /[0-9]+\.[0-9][0-9]$/ | Invalid Currency | Valid currency is Dollars followed by Cents, ##.## |
After you create the Zapatec.Form, call Zapatec.Form.addDataType to add your Custom Data Type.
Here is the code to create the currency Custom Data Type.
<script type="text/javascript"> // create a custom data type Zapatec.Form.addDataType( 'zpFormCurr', 'A Currency', /^.[0-9]+\.[0-9][0-9]$/, "Invalid Currency", "Valid currency is ##.##", null ); </script>
Masks provide an easy way to define a valid field format. When a user types in a field that is specified by a mask, the form visually indicates the mask, which simplifies data entry as well as preventing the user from making an invalid entry. See the Masks demo
For example, to define a mask for Social Security Number, first select the mask rule:
3 digits
followed by a dash
followed by 2 digits
followed by a dash
followed by 4 digits
Thus, the mask rule is "000-00-0000", where 0 indicates a place-holder for a required digit. To implement the mask rule for the social security number field, assign the mask rule to the zpFormMask class of the input element. This directs the Zapatec Form to apply a mask with a rule of 000-00-0000.
Here is the code that defines the social security number mask in Masks Demo
<label class='zpFormLabel'>US SSN 000-00-0000</label> <input class='zpFormMask="000-00-0000"' value="" size="15" name="ussn" type="text" />
The following table shows the available mask placeholders.
Symbol | Description |
---|---|
0 | Required digit (0 through 9) |
L | Required letter (A through Z) |
A | Required letter or digit |
& | Required character (any kind) or a space |
\ | Character that follows is displayed as a literal character |
Maxlength property is not compatible with zpFormMask. It is better to use zpFormMask to limit user's input.
Another useful feature that can be added to your forms is restricting the set of keystrokes that user is allowed to type in a field.
See the Limit Allowed Keystrokes demo.
To limit keystrokes, add the appropriate zpFormAllowed or zpFormAllowedChars class to the input element. You can specify:
alphanumerics only - zpFormAllowed-w;
digits only - zpFormAllowed-d;
whitespace only - zpFormAllowed-s;
letters only - zpFormAllowedChars = "A-Za-z";
specific characters - zpFormAllowedChars = allowed_chars.
For example, the following code uses zpFormAllowed-d to limit keystrokes to digits in this field.
<label class='zpFormLabel'>Digits only</label> <input value="" size="15" name="digits" type="text" class='zpFormAllowed-d' />
To limit keystrokes to alphanumeric keys, use zpFormAllowed-w, to white space use zpFormAllowed-s.
For all letters or specific letters use the zpFormAllowedChars class.
This example limits keystrokes to letters only:
class='zpFormAllowedChars=A-Za-z'
and this one to only the AaBbCc123 keys:
class='zpFormAllowedChars=AaBbCc123'
The Zapatec Form provides a way to validate forms automatically based on the server response. See the Submit form to server using AJAX demo.
The Zapatec Transport facility provides your form with automatic client-side and server-side validation. See the Validate single field using AJAX demo.
To enable validation based on the server response, define the optional asyncSubmitFunc
as a callback function. This function is called after a success response is received from the server. You can then close the window, clear the form, etc. See asyncSubmitFunc property for more details.
A failure response from the server is handled in the same way the client-side errors are handled, as described in submitErrorFunc property.
The server response should be a valid JSON string in one of the following formats:
Server Validates Form:
{"success": true}
Server Error, No Details:
{"success": false}
Server Error, Details:
{ "success": false, "generalError": "Human readable error description", "fieldErrors": { "INPUT-fieldName1": "Human readable error description", "INPUT-fieldName2": "Human readable error description", ... } }
If serverCallback configuration option was chosen, the server must use it and pass a JSON with submit details to it. Example for PHP:
<?= $_POST["callback"] ?>({"success": true});
You can use the following parameters in the input class specification of a field to control server-side validation:
zpFormValidate
= URL where to send request;
zpFormValidateMethod
= HTTP method to use (GET, POST, etc.); default is GET;
zpFormValidateParam
= name of the parameter; default is the field name;
zpFormValidateQuery
= query string to be added to the request.
For example:
<input class='zpFormRequired zpFormValidate="validate.php" zpFormValidateMethod=GET zpFormValidateParam="my_var" zpFormValidateQuery="ajax_check=true"' value="" size="40" name="name" type="text" />
See the Validate single field using AJAX demo.
You can automatically fill other form fields depending on the typed value. The other field values will be retrieved from the server. Use the following parameters in the input class specification of a field to control this process:
zpFormFillUrl
- a URL where to send request;
zpFormFillMethod
- the HTTP method to be used (GET, POST etc). The default is GET;
zpFormFillParam
- the name of the parameter. The default is the field name;
zpFormFillQuery
- the string that will be added to the request query.
For example:
class='zpFormFillUrl="ajax_fill.php" zpFormFillMethod=GET zpFormFillParam="my_var" zpFormFillQuery="ajax_check=true"'
will be transformed into:
ajax_fill.php?ajax_check=true&my_var=<CURRENT_FIELD_VALUE>
See Ajax fill demo.
You can configure the form to display feedback icons before or after the input fields. The rules pertaining to the status image for field validation are based on the parameter passed by statusImgPos and the rules that are embedded in the CSS files located in the themes directory. The CSS file should be included in your web page to display the images according to the rules in these files.
If you do not want any status images in the form, delete the rules that manipulate the status image (span.zpStatusImg) from the CSS.
The images are included in nested spans whose classes vary according to the status of the data. As a result, you can configure the images using simple CSS rules.
The following is the list of spans from the outermost to the innermost.
"zpIsRequired" or "zpNotRequired" - Is this field required?
"zpIsEditing" or "zpNotEditing" - Is the user editing this field?
"zpIsEmpty" or "zpNotEmpty" - Is this field empty?
"zpIsValid" or "zpNotValid" - Is this field valid?
Always "zpStatusImg" - This is the one styled.
Here are the contents rules pertaining to the status image:
/* "zpStatusImg" class images for form fields -- apply appropriate rules here. The script auto-applies one of each of these CLASS attributes to a series of nested <span>s with an innermost .zpStatusImg class <span> we style: 1) "zpIsRequired" or "zpNotRequired". 2) "zpIsEditing" or "zpNotEditing". 3) "zpIsEmpty" or "zpNotEmpty". 4) "zpIsValid" or "zpNotValid". 5) Always "zpStatusImg", this is the one styled. */ * html span.zpStatusImg { /* MSIE fix to force "hasLayout" for opacity. */ display: inline-block; } span.zpStatusImg { padding: 0px 12px; height: 18px; line-height: 18px; background-repeat: no-repeat; background-position: center; opacity: 0.66; filter: alpha(opacity=66); margin-left:5px; } .zpIsEditing span.zpStatusImg { opacity: 1.0; filter: alpha(opacity=100); } .zpIsRequired span.zpStatusImg { background-image: url(icons/required.gif); } .zpIsEditing .zpNotEmpty span.zpStatusImg { background-image: url(icons/editing.gif); } .zpNotEditing .zpNotEmpty .zpNotValid span.zpStatusImg { background-image: url(icons/required_invalid.gif); } .zpIsValid span.zpStatusImg { background-image: url(icons/validated.gif); }
In this scenario, the user is editing (zpIsEditing) and the field is not empty (zpNotEmpty). Here is how the nested code looks (DHTML and CSS) to render the form validation images.
<!-- Editing the field --> <span class="zpIsRequired"> <span class="zpIsEditing"> <span class="zpNotEmpty"> <span class="zpIsValid"> <span title="" class="zpStatusImg"> </span> </span> </span> </span> </span>
Notice how the CSS selector is rendered producing the image that looks like a pencil.
.zpIsEditing .zpNotEmpty span.zpStatusImg { background-image: url(icons/editing.gif); }
The zpFormMultiple class lets the form display an indeterminate number of fields. This is useful when the number of fields needed on the form is unknown prior to interaction with a user, for example, fields to add data for one or more children. This feature displays the '+' button next to the input field, which, if activated by the user, duplicates the field so the user can enter another set of data. It also provides the '-' button to enable the user to remove a field that has been added.
See the Multiple Fields Demo.
Use the zpFormMultiple or zpFormMultipleInside class to enable the multiple feature. zpFormMultiple places the '+' after the element, while zpFormMultipleInside places it inside the element. If the class is added inside a row in a table, a new cell is appended to the row to hold the '+' and '-' signs.
This code lets the user add multiple address fields, placing the '+' and '-' signs inside the element.
<label class='zpFormLabel'>Address</label> <div style="margin-left: 10.2em" class="zpFormMultipleInside"> <input class='zpFormRequired' value="" size="40" name="address" type="text" /> </div>
This code lets the user add multiple rows to a table and automatically creates an additional cell for the '+' and '-' signs.
<tr class="zpFormMultiple"> <td valign="top" align="center"><input type="text" name="name"></td> <td valign="top" align="center"><input type="text" name="surname"></td> <td valign="top" align="center"><input type="text" name="address"></td> </tr>
To prevent the uncontrolled proliferation of fields, you can set a limit to the number of cloned fields that a user can add using the zpFormMultipleLimit option. The following example limits the number of fields that can be added to three, so that after three fields are added to the form, the user no longer gets a '+' that makes it possible to add more fields.
<tr class="zpFormMultiple zpFormMultipleLimit=3">
You can provide a callback to set the conditions under which a form displays or hides a field. If the callback returns true, the field is displayed. If it returns false, the field is hidden.
This feature is particularly useful for a form in which the user should fill in some fields only when other fields have a particular value.
You can use the zpFormDisplayWhen property if you do not want the hidden block to occupy any space in the form. The following code sets the zpFormDisplayWhen property for the fieldset. It will be displayed if showPersonalInfo
function returns true. This function should be created by developer. See the code:
<input type="checkbox" id="show_personal_info" /> Show personal info<br /> <fieldset class="zpFormDisplayWhen=showPersonalInfo"> <label class='zpFormLabel'>Date of Birth</label> <input value="" size="23" name="dob" type="text" class='zpFormDate zpFormMask="00\/00\/0000"'> <br /> ... </fieldset>
In this example, the callback simply returns the value of a checkbox, though your function might be more complicated:
function showPersonalInfo(){ return document.getElementById('show_personal_info').checked }
If you want the hidden fields to use their space in the form, even when they are hidden, use the zpFormVisibleWhen property instead.
<fieldset class="zpFormVisibleWhen=showOnlineInfo">
See the Conditional Fields demo.
You can use the Zapatec Form addChangeHandler(function) routine to specify a special callback for events associated with different fields within the same form.
See the Change Handlers demo for an example.
To specify a callback, add the code for your custom event handler and then call addChangeHandler with the name of your handler:
form.addChangeHandler(togglePersonalInfo);
Be cautious and efficient with your code when using this feature, as your callback will be invoked on every form event.
When you enable the auto-complete feature, a user can enter some text in a field, and then select suggestions for completing the string.
See the Auto-Complete with Suggestions demo.
To fetch the auto-complete suggestions from the server, specify the appropriate zpFormSuggest parameter in the input class of the field.
The zpFormSuggest parameters are:
zpFormSuggest
: a URL where to send the request;
zpFormSuggestMethod
: the HTTP method to use (GET, POST, etc.); default is GET;
zpFormSuggestParam
: the name of the parameter; default is the field name;
zpFormSuggestQuery
: the string that will be added to the request query.
For example:
<input class='zpFormSuggest="suggest.php" zpFormSuggestMethod=GET zpFormSuggestParam="field1" zpFormSuggestQuery="ajax_suggest=true"' value="" size="40" name="suggest_state" type="text" />
Zapatec translates this as
suggest.php?ajax_suggest=true&field1=<CURRENT_FIELD_VALUE>
and sends it to the server.
The server must respond with a JSON object in the following format:
{ "success" : true, //true/false - if request processed successfully. "generalError": "Human readable error description" // if success == false "header": [ // table header description. Optional. { name: "Col name1", // text to display in column header style: "color: blue", // apply this style to this header colStyle: "color: blue" // apply this style to each cell in this row }, { name: "Col name2", // text to display in column header className: "custom", // add this class to this header colClassName: "customCol" // add this class to each cell in this row } ], "body": [ // array of data to display in rows ["str1, col1", "str1, col2"], ... ] }
To supply the auto-complete suggestions from the client (web page), set the class of the field to either zpFormAutoComplete or zpFormAutoCompleteStrict and list the suggestions as options.
<select name="state_name" class="zpFormAutoComplete"> <option></option> <option>Alabama</option> <option>Alaska</option> ... </select>
If you use zpFormAutoCompleteStrict, the field value entered by the user will pass validation only if it is equal to one of the suggested options, including case. With zpFormAutoComplete, the user's input is valid even if it does not match any of the suggestions.
You can make Form to display messages on any language.
You just have to set langID,
langCountryCode
and langEncoding
parameters.
langId - is a 3-letter acronym taken from http://www.loc.gov/standards/iso639-2/php/code_list.php By default langID
is set to "eng".
langCountryCode
- contains two letter country name acronym (see ISO 3166) . Optional. You can omit it.
langEncoding
parameter is for character encoding. By default it is undefined.
If you intend to use language other than English, you also have to add this line of code to your page:
<script type="text/javascript" src="zpform/lang/por_br-utf8.js"></script>
It will attach message file with resources for this language. Now it is possible to use langID
: por (Portuguese), langCountryCode
: br (Brazil) and langEncoding
: utf8.
If you forget to attach message file with resources for this language, you'll get alert after the form is initialized. After that all the messages will be system messages instead of translated.
Use formObj.getMessage(key,[sub1,sub2...])
to get localized message.
First parameter is a key for which you want to get localized message. All the other parameters are optional, they represent the substitutions (see Substitution section).
Use formObj.sprintf()
to format and insert values in the string. For example, you can use getMessage()
to get the string and then insert values in it using sprintf()
.
You can use tokens %1, %2, %3 in every string. Method getMessage
can accept as many parameters as you wish. Each parameter that you have listed will be substituted by the given arguments and returned by getMessage(). If you have specified more arguments than the number of tokens in the appropriate line, then all the arguments will be shown "as is".
You can create or modify the resource file for you language. Use zpform/lang/default.js as a template. Use remarks and comments to make the correct translation.
Do not remove any keys from that file, even if you consider them irrelevant. Form may not function properly after that.
After you've done with translation - rename it considering these 3 rules:
Short form of the language goes first («eng» for English, «fre» for French etc).
To obtain the correct abbreviations - go to http://www.loc.gov/standards/iso639-2/php/code_list.php
Optionally, you can specify the region using two letters abbreviation. It must be separated from language using "_".
To obtain the correct abbreviations - go to http://userpage.chemie.fu-berlin.de/diverse/doc/ISO_3166.html
If this file uses some specific character encoding, write it after "-".
Use .js extension for the file.
fre_be-utf8.js - stands for French, region - Belgium and uses Unicode UTF-8.
This property is intended to give developers an opportunity to do some custom actions after files were sent using AJAX like approach. The standard solution using XMLHTTPRequest is not suitable in this case. You need to specify the parameter using serverCallback property. The following string should possess the name of the HTTP request parameter that holds the name of the function that is called to finish form submission.
The server must respond with following response (example for PHP):
<html><body><script type='text/javascript'> <?= $_REQUEST["___SERVERCALLBACK PROPERTY VALUE___"] ?>(___YOUR JSON RESPONSE___); </script></body></html>
___SERVERCALLBACK PROPERTY VALUE___ should be substituted with actual serverCallback config option value.
Replace ___YOUR JSON RESPONSE___ with your actual server JSON response.
See ajax_server_callback.html demo.
Our Form widget provides plenty of ways to make interaction between browser and server more efficient and 'comfortable' for both. You can perform client side validation of data entered. Consequently, you can point to an error without sending request to server and waiting till it will be processed and sent back. However, due to the nature of JavaScript the browser makes it possible for the user to view the script and turn it off. So, we strongly recommend you to perform additional checking on server side to avoid the situation where undesirable input was entered into data storage, etc.
Also, it is a good idea to use asyncSubmitFunc to inform the user about successful post.
Our Form was designed to be a fully independent client-side component. This means that although it has some mechanism of interaction with server-side, it doesn't care about particular technology being used on server. It can be any version of PHP, ASP, JSP, Ruby, or any other technology of your choice. The communication interface it supports is very simple so the only thing your server-side application needs to be able to do is to process regular requests and return response with certain order of key/value pairs. To sum it up, you have a freedom of choice when it comes to server-side platform. Another issue is the general limitations imposed on ANY JavaScript that is run on ANY browser. Our Form widget (as well as any other JavaScript created component) CANNOT do mailing, conversion of data into some file formats, determining the size of files attached, and things like that without involving some server-side applications.
While using multiple fields, there are often many problems with guessing what names the newly created elements have. You can use the names given to the newly cloned elements by Form script or you can create your custom function that will be called each time new element is cloned and assign it to multipleCallback config option. The first approach is very simple because it does not require any coding to be done. Newly created element gets the name of its original + “-” sign + increment number (index). So, if the original element name was 'address', its clones will be 'address-1', 'address-2', etc. Remember that after you delete the element, its increment number (its index) gets released, it will be assigned to the next element in line. So, for example, if you had address, address-1, address-2, address-3 and then deleted address-1, then address-2 will become address-1, address-3 will become address-2, and so on. See the demo.
The second approach lets your custom function do the naming instead of the Form script. As already mentioned, it should be assigned to multipleCallback config option. It receives 4 parameters:
original
, cloneParent
, cloned
, children
. To explain what they stand for lets imagine a situation where you have a multiple field that is inside the DIV. This DIV has its class attribute equal to 'zpFormMultipleInside' and contains a label and an input field. Each element has its name or id. When you press '+' button to clone this field, the function that is assigned to multipleCallback is called for the first time. The original
parameter will be the reference to the original DIV that we are going to clone from. The cloneParent
parameter will be the reference to the newly created element (just cloned DIV, yet empty inside). The cloned
parameter will be the same as cloneParent
(because on the first call the currently cloned element is DIV itself, not its children). children
is an empty array yet. Then this function is called one more time to clone label that is inside original DIV. The original
and cloneParent
parameters will have the same value as during the previous call. cloned
will be the reference to this newly created label and children
array is still empty. Then the function is called for the third time to clone the remaining input field. As you might guess already, the first two parameters are the same as before. cloned
references the newly created input field and children
array gets populated with the reference to the DIV, because on this stage we have done with the cloning of the original DIV. As you can see, we have cloned all elements (DIV, label, input field) that have had name or id. So for each element you can have a line of script that can take the reference of the newly created element and give it some name or id depending on your business logic.
If then you decide to clone this original DIV one more time, every parameter will be the same except that the cloneParent
will be the reference to this DIV, not to previous one, the same with cloned
– it will be the reference to the elements that are being created each time. children
array will already have one value – reference to the previous DIV. When done with cloning of elements – reference to the newly created DIV will be added to it.
You can limit the number of the allowed cloning operations by adding this line to the cloned fieldset (DIV).
class ="zpFormMultipleLimit=5"
Now it will be possible to create only 5 clones. See the demo.
Very common error is the absence of attention when setting up Form on you environment. Sometimes people make spelling errors writing paths in head section, others change the original directory structure (although it is possible to work with changed structure – we don't recommend to do this without knowing which inclusion in the HEAD section is needed to be changed after that) without changing the paths to script in the HEAD section, there are people who make mistakes in script. If you don't see your page layout is being repainted according to CSS theme, or if there is no validation mark (if used) next to fields that are specified as required to have validation, or if you see that your browser is throwing errors like “Zapatec is not defined”, etc – this means you have made a mistake during set up process. Please re-read the appropriate section of this manual.
If your Form has many conditional fields (fields that are being constantly checked by script to see if they correspond to some value) you may experience a problem with performance. Browser starts to work slowly so you are not able to type at a decent pace and other productivity-related issues get revealed. To avoid this kind of situation, we suggest you to use conditionalEvents config option. It allows to specify for what events your conditional fields are checked, since by default it checks for all. Specify only those events that needed, it can't be one or several but pay attention to the syntax – its an array of strings.
This event is invoked when any of the fields changes its value. In some cases, it is not necessary that the form changes its value - it may remain the same. For example, the user may highlight the content of the field, copy it to the clipboard and then paste it. Moreover, this event is also called under conditions described for the booleanValueChanged.
This event is called when the checkbox or radiobutton were toggled. The value in this case may not be changed.
Each form acquires the browser Event object as a first argument. Using Zapatec.Utils.getTargetElement(eventObj), where eventObj is a n acquired exemplar of event, you can get a reference to the element that generated event. For example, for the keyPress it returns the field where the button was pressed.
Moreover, the "all" event as the second argument acquires the string with the name of the event being called (for example, "focus", "keyUp", etc.).
Before using event, it is recommended to think of the cases when it should be called. If the function just checks the checkbox value, it is better to assign it to the booleanValueChanged. If you need to change any content of the page while the user is typing in the field, try to use valueChanged or keyUp.
It is not recommended to use the "all" event. This may slow down your form if it consists of multiple fields.
You can add events by using eventListeners config option (see the demo) or with the help of form method zpFormObj.addEvents, where the first argument is a function to be called and the second - the list of events for which it should be called.
The event list may be either an array ("keyDown", "keyPress", "keyUp" ) or a single string (for example, "blur").
If the list is not defined or is empty, the "all" event will be used.
The addEvent function is instantly called when used for adding the event. Under this conditions you should not specify the first event property.