Click here to Skip to main content
13,762,563 members
Click here to Skip to main content
Add your own
alternative version

Stats

9.1K views
319 downloads
12 bookmarked
Posted 11 Sep 2015
Licenced CPOL

A JavaScript Form Generator

, 2 Oct 2018
Rate this:
Please Sign up or sign in to vote.
A JavaScript Form Generator

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.

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:

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.

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.

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:

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).

...
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,&#x2718,30,,Cancel form;
B,fg_Reset,&#x21B6,30,,Reset form;
B,fg_Ok,&#x270E,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 &#x270E (✎).

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]

...
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).

...
Fgen = new formGen("fg")
<span style="display: inline !important; float: none; 
background-color: rgb(251, 237, 187); color: rgb(0, 0, 0); font-family: Consolas,
"Courier New",Courier,mono; font-size: 12px; font-size-adjust: none; font-stretch: 100%; 
font-style: normal; font-variant: normal; font-weight: 400; letter-spacing: normal; 
line-height: normal; orphans: 2; text-align: left; text-decoration: none; text-indent: 0px; 
text-shadow: none; text-transform: none; -webkit-text-stroke-width: 0px; white-space: pre; 
word-spacing: 0px;">$("Agree").addEventListener("click",function() 
{$('Start').disabled = !this.checked;},true);
$('Start').disabled = true;</span>
...
<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:

...
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 present a file upload, 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):

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:

<?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";}
?>

Note

  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:
    .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;}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Member 4206974
Software Developer Condor Informatique
Italy Italy
Computer literacy (software) : Languages: PHP, Javascript, SQL Autoit,Basic4Android; Frameworks: JOOMLA!
Teaching/Training skills on Office, WEB site development and programming languages.
Others : WEB site development.
UNDP Missions
feb – may 2003 Congo DR Bukavu: ground IT computer course
nov 2003 Burundi Bujumbura: Oracle Data Base course
feb 2005 Burundi Bujumbura: JAVA course
mar 2005 Mali Kati: MS Office course
oct 2006 Mali Kati: MS Office course
jun 2006 Burkina Faso Bobo Dioulasso: MS Office course
jun 2007 Burkina Faso Bobo Dioulasso: MS Office course
may 2007 Argentina Olavarria hospital: Internet application for access to medical records
apr 2008 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
jun 2008 Niger Niamey: analysis of the computing needs of the Niamey hospital
may 2009 Burkina Faso Ouagadougou: MS ACCESS and dynamic Internet applications
oct 2010 Niger Niamey: analysis of the computing needs of the Niamey hospital (following)
Region Piedmont project Evaluation
mar 2006 Burkina Faso, Niger
mar 2007 Benin, Burkina Faso, Niger
sep 2008 Benin, Burkina Faso, Niger
Others
feb 2010 Burundi Kiremba hospital: MS Office course
feb 2011 Congo DR Kampene hospital: MS Office course

You may also be interested in...

Comments and Discussions

 
QuestionMessage Closed Pin
3-Oct-18 9:55
memberAllDigitalUpdate3-Oct-18 9:55 
GeneralMy vote of 5 Pin
shahani1102-Oct-18 22:43
membershahani1102-Oct-18 22:43 
GeneralMy vote of 5 Pin
E. Scott McFadden2-Oct-18 7:46
professionalE. Scott McFadden2-Oct-18 7:46 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.181112.1 | Last Updated 2 Oct 2018
Article Copyright 2015 by Member 4206974
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid