5

A JavaScript Form Generator - CodeProject

 2 years ago
source link: https://www.codeproject.com/Articles/1029517/A-JavaScript-Form-Generator
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

Image 1

Introduction

This article is about a JavaScript object (FormGen) for creating and managing Forms[1]; FormGen is sufficiently generalized for create a wide set of forms, from simple message box to relatively complex forms with text field, combos, radio buttons and so on[2]; moreover it is only an informal and not exhaustive presentation of the package.

The package is evolving by functionalities that arise from my use; this impacts not only on the source but also on documentation, code cleaning and increase reliability. Briefly some last implementation are:

  • Added control of field and function existence on Event pseudo type.
  • Added the field fg_Changed that contains the list of fields modified.
  • Added the pseudo event enter that permits the form submission by enter key  on text field.
  • Added the IB (inline button) type that acts like a comment (see image below).
  • Added CE (comment error) and CS (comment separator) types.
  • Added a pseudo type Dict[ionary] for an internationalisation (see below).
  • Added the possibility to create movable forms (see documentation for use).

Image 2

Using the Program

The form generator is in formgen.js script, which contains the object function formGen; this function can be invoked or used for creating a new object:

JavaScript
Copy Code
formGen(idContainer[,control_list])
fGenObject = new formGen(idContainer[,control_list])

where idContainer is the id of an HTML tag that will host the generated form and control_list is the list of controls with possibly other information (pseudo controls) for managing the form; if this parameter is omitted, formGen assumes that the list is in the tag container.

If the idContainer is omitted, it is created with id fg_PopUp and class fg_PopUp useful for creates movable forms.

Every control description is characterized by a list of attributes comma separated: Type, Field Name, Field Label, Length and Extra:

  • Type is the control type, this is indifferent to the case.
  • Name is the control name, the case is significant (generally become a name and id of the control).
  • Label is the label of the control.
  • Length is the length of the control.
  • Extra is an extra field for add information to the control (this depends on the type).

Every description is separated by a semicolon.

Note

The possibly commas, semicolons, equal and & signs in labels and extra fields, must be coded respectively by \x2C, \x3B, \x3D and \x26.

Starting from version 0.2.12 the attributes can be enclosed in ' or " in order to contains the above characters.

Among the controls, there are different types of text controls, lists, buttons, slider, radio button and check box; the list can also contain some pseudo controls (with a semantic slightly different):

  • Form for telling how to manage the form when it is submitted, its syntax is: Form, name, caption, uri, function;
  • Defaults for insert value on controls;
  • Control for executing some checks on the fields before submitting the form;
  • Below and After for moving the buttons from the default position, at the bottom of the form, below or after (at right) of a control;
  • Get for obtaining data, useful for populating the form or update lists.

formGen inserts three standard buttons buttons: Ok, Reset and Cancel, depending on the controls in the form, for example, if there is only one combo or radio button set, no buttons are presents because the choice on item exits the form try:

JavaScript
Copy Code
Form,frm,,echo.php;
CMB,Unit,Measure Unit,,,|=Linear,mm=millimeter,cm=centimeter,m=meter,
km=kilometer,|=Weight,g=gram,kg=kilogram,t=ton;

However, we can put custom buttons or change the caption or use graphics buttons replacing the standard buttons (whose names are fg_Ok, fg_Cancel, and fg_Reset) (try).

JavaScript
Copy Code
...
function infoPSW(frm) {
	alert("Password from 6 to 12 characters.\nand at least one number and 
           one capital letter and one letter")
}
formGen('fg');
...
<div id=fg>
P,psw,Password,15,Insert password;
B,Info,?,25,infoPSW;
B,fg_Cancel,✘,30,,Cancel form;
B,fg_Reset,↶,30,,Reset form;
B,fg_Ok,✎,30,,Go!;
After,psw,Info;
Control,psw,required,pattern=(?\x3D.*\d)(?\x3D.*[A-Z])(?\x3D.*[a-z]).{6\x2C12};
</div>
...

Note the use of Unicode characters for the button's caption like ✎ (✎).

Form Presentation

The data are presented in the order in which they appear in the parameters list, except for the custom buttons that appear together the standard buttons inserted by FormGen at the bottom of the form; therefore, it is possible to insert custom buttons and check boxes at the right or below a control (by Below and After pseudo controls).

With CSS style, we can control the presentation because the form is displayed using a table tag which has a class name fg_Table, the buttons have the class name fg_Button or fg_Gbutton. The first td tag of every rows has class name fg_Label.

Controls on Data

The pseudo control Control or Check allows to perform some controls on data:

  • greater or less a value
  • formally correct mail address
  • not empty field
  • match a regular expression

Those controls occur when:

  • the control loses the focus
  • the user inputs a numeric field
  • the form is submitted

In the sample below, a numeric floating field is checked in input, on loss of focus and when the form is submitted try [3]

JavaScript
Copy Code
...
NF,Number,,12,Insert Floating number;
Control,Number,min=-200,max=200,pattern=^[-+]?\d{1\x2C3}(\.\d{1\x2c2})?$;
...

Handle Controls and Events

We can enter the management of events using the ID of the control, namely the name of the control. Also, in the extra field of a button, we can set a function that will be invoked when the button is clicked with argument the form itself (see this fragment below) (try).

JavaScript
Copy Code
...
Fgen = new formGen("fg")
$("Agree").addEventListener("click",function() 
{$('Start').disabled = !this.checked;},true);
$('Start').disabled = true;
...
<div id='fg'>
GB,Info,images/info.png,,infoPSW,Info;
CKB,Agree,Consent cookies?,,I agree;
B,Start;
</div>

When the Form is Submitted

The data are checked as indicated in the pseudo type Check (if it exists), in case of errors, the form is not submitted and the fields in error are bordered in red; it also generated an alert.

The submission depends on parameters URL and function of pseudo type Form:

  1. only URL: the response replaces the source page
  2. URL and function: function receives the answer, via a built-in Ajax module, from URL
  3. only function: function is called with argument form, obviously it needs a local elaboration

Submit in a New Page

In case 1) above for display in a new page, we insert a custom button which, in the extra field, contains the name of a function that will handle the submission:

JavaScript
Copy Code
...
Fgen = new formGen("result")
...
function myHandler(frm) {		                // the function receive the form	
	var aErrors = Fgen.check(frm);
	if (aErrors.length > 0) {alert("Errors:\n"+aErrors.join("\n"));return;}
	frm.encoding = "multipart/form-data";		// if there is a file to upload
	frm.target = "_blank";				        // in new window
	frm.submit();
}
...
Form,frm,Complete Control form,x.php;
B,Start,,,myHandler;
...

Note that the user must carry out any checks on the fields, and, if a file upload is present, he must set the property encoding.

Advanced Use

The pseudo type Get can be used to retrieve data from INTERNET via the internal Ajax function for populate (or change) values on Combo box or Lists or to populate the form with default values, for example with data from database.

Get needs a URI, i.e., a script on an Internet site that provides the data whose structure must have the syntax expected in extra field of CMB or L or, in case of defaults is the structure expected for pseudo type DEFAULTS (see example below):

JavaScript
Copy Code
Form,frmg2,Form Generator 2,echo.php;
CMB,WidgetType,Widget Type;
CMB,Hellas,Greek letters;
List,Town;
B,fg_Ok,✎,40;
B,fg_Cancel,✘,40,,Cancel Form;
B,fg_Reset,↶,40,,Reset Form;
Get,*,getSample.php?Type=Defaults;
Get,WidgetType,getSample.php?Type=Type;
Get,Town,getSample.php?Type=Towns;
Get,Hellas,getSample.php?Type=Hellas;

Here is the PHP script that handles the requests:

JavaScript
Copy Code
<?PHP
$type = $_REQUEST["Type"];
if ($type == "Type") {
	echo "|=Buttons,B=Button,R=Radio button,RV=Vertical Radio button,"
	."|=Lists,CMB=Combo box,L=List,"
	."|=Texts,C=Comment,F=File,H=Hidden field,N=Numeric,NS=Numeric signed,"
	."NF=Numeric with decimals,P=Password,T=Text,U=Unmodifiable text,"
	."|=Others,CKB=Check box,S=Slider";
}
if ($type == "Hellas") {echo "Alfa,Beta,Gamma,Delta";}
if ($type == "Towns") {echo "London,Paris,Rome,Turin,Zurich";}
if ($type == "Defaults") {echo "Town=Turin,Hellas=Alfa,WidgetType=F";}
?>

Furthermore, the pseudo-type GET has been enhanced adding a timeout parameter to allow periodic updating of comments, texts and of new control type Image:

Copy Code
Form,frm,,echo.php,receiveData;
C,Time,Clock;
T,wField,IT Cite,200;
Image,Image,,200;
GET,Time,getSample.php?Type=Time,60000;
GET,wField,getITCite.php,10000;
Get,Image,getImage.php,11000;
Image 3

Movable forms

In the SandBox there is an example of movable form (and internationalization).

This is achieved through a form generated without indicating the creation tag or indicating a non-existent tag, so FormGen generate a div tag with class fg_PopUp, the form must have the form pseudo type in order to be generate a title row.

At this point the user can add a class to the title in order to show the move cursor and must include some JavaScript for move the form (theSandBox includes the script moveItem.js).

Widget
List

Copy Code
Form,ft,Try Sand Box,echo.php,receive;
T,Text1,Text 1,,place holder;
RV,vRdb2,vRdb 2,,North,South,West,East;
JS
Copy Code
function movableForm(widgetList) {
	if($("fg_PopUp")) $("fg_PopUp").remove();
	Fgen = new formGen("",widgetList)
	var link = $("fg_PopUp")
	link.style.top = 0.5 * (window.innerHeight - link.offsetHeight);
	link.style.left = 0.5 * (window.innerWidth - link.offsetWidth);
	$("ftfg_Title").classList.add("fg_Movable")
//	$("ftfg_Title").className += " fg_Movable";	// old browsers?
	$("ftfg_Title").addEventListener("mousedown", dragStart.bind(null, event, "fg_PopUp"))
}
CSS
Copy Code
.fg_PopUp { 
   width: auto;
   height: auto;	
   position: absolute;
}
.fg_Movable {
   width: 100%;
   cursor: move;
}
  1. ^This is one of some form generators (for Autoit, Powershell, Basic4Android) which can be found in my site.
  2. ^Some functionality requires HTML5 (input type Data).
  3. ^There are some simple styles:
    JavaScript
    Copy Code
    <font size="2">
    .fg_Button {font-size:10pt;width:70px;height:22px;cursor:pointer;margin:0px 3px;
        background:silver;line-height: 1.25;}
    	fg_GButton {border:0;cursor:pointer;vertical-align:middle;padding:5px;}
    	table {border: 1px solid #111;padding:3px}
    	th {font: bold 9pt Arial;text-align: center;padding:5px;
        vertical-align:top;background-color:#eee;}</font>

Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK