Click here to Skip to main content
15,608,553 members
Articles / Web Development / HTML
Article
Posted 11 Sep 2015

Stats

47.5K views
2.1K downloads
64 bookmarked

A JavaScript Form Generator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (26 votes)
24 Nov 2021CPOL6 min read
FormGen, a JavaScript Form Generator
In this article, you will learn about a JavaScript object, FormGen, for creating and managing Forms.

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

JavaScript
...
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
...
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
...
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
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
<?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:
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
Form,ft,Try Sand Box,echo.php,receive;
T,Text1,Text 1,,place holder;
RV,vRdb2,vRdb 2,,North,South,West,East;
JS
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
.fg_PopUp { 
   width: auto;
   height: auto;	
   position: absolute;
}
.fg_Movable {
   width: 100%;
   cursor: move;
}


 

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:
    JavaScript
    <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>

License

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


Written By
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

Comments and Discussions

 
QuestionThis is holesome. Pin
Mat Kordell20-May-22 0:10
professionalMat Kordell20-May-22 0:10 
GeneralMy vote of 5 Pin
Ștefan-Mihai MOGA24-Nov-21 4:40
professionalȘtefan-Mihai MOGA24-Nov-21 4:40 
GeneralRe: My vote of 5 Pin
Member 420697424-Nov-21 5:58
Member 420697424-Nov-21 5:58 
QuestionJavascript form generator Pin
Member 1543476418-Nov-21 9:22
Member 1543476418-Nov-21 9:22 
AnswerRe: Javascript form generator Pin
Member 420697419-Nov-21 4:06
Member 420697419-Nov-21 4:06 
AnswerRe: Javascript form generator Pin
Member 420697423-Oct-22 4:58
Member 420697423-Oct-22 4:58 
GeneralMessage Closed Pin
29-Nov-20 2:58
vikas ayadav29-Nov-20 2:58 
Questionbig Pin
dejan filipo25-Nov-20 20:23
dejan filipo25-Nov-20 20:23 
GeneralMy vote of 5 Pin
shahani1102-Oct-18 21:43
shahani1102-Oct-18 21:43 
Very nice thought
GeneralMy vote of 5 Pin
E. Scott McFadden2-Oct-18 6:46
professionalE. Scott McFadden2-Oct-18 6: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.