Click here to Skip to main content
15,867,453 members
Articles / Web Development / HTML

A JavaScript Form Generator

Rate me:
Please Sign up or sign in to vote.
5.00/5 (29 votes)
15 Jan 2024CPOL7 min read 58.6K   2.3K   72   9
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 creating a wide set of forms, from simple message box to relatively complex forms with widgets like 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 implementations are:

  • Added control of field and function existence on Event pseudo type.
  • Added the fields:
    • fg_Changed that contains the list of fields modified,
    • fg_TimeStamp whose content is the date and time of submission,
    • fieldName_Group the possibly group of combo box item,
    • fieldName_Exposed the combo box item text.
  • 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.
  • Added the possibility to create movable forms (see the documentation to learn how to use it).

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 widgets 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 widget description is characterized by a list of attributes separated by comma: Type, Field Name, Field Label, Length and Extra:

  • Type is the widget type, this is indifferent to the case.
  • Name is the control name, the case is significant (generally it become a name and is part of the 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 widget 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 widgets, there are different types of text controls, lists, buttons, slider, radio button , check box, hidden fields..., 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;
  • 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, update lists or change fields and or images at predefined intervals .
  • Event for associate an event to a form component: the event can be handled by a local function (JaveScript) or on the server, for example by a PHP script. The response can be sent to a local script or entered directly on a DOM component. 

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 some others controls)  at the right or below a control (by Below and After pseudo types).

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 type 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
  • control by a custom function

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

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

Handle Controls and Events

We can enter the management of events using the ID of the widget. 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>
However, the simplest way to handle events is by the pseudo type Event that allows to assign to an element, through his name, both the script server and the JavaScript that will process the response; moreover if instead of the JavaScript function is indicated an element of the DOM, in particular an INPUT, or an IMG or a DIV tag, it will accept the data, see the example below.
Form,fHBook,Static Form,echo.php,receive,static;
u,Text, ,5;
IB,Clock,images/clock.png,,,Get Time;After,Clock,Text;
Event,Clock,click,getSample.php?Type=Time,<code>Text</code>;
IB,xExcel,images/excel.png,,alert:Create Excel file,'Create Excel file';
IB,ShowImage,images/faro.ico,,,Show image;
IC,Img, ,200;
Event,ShowImage,click,getImage.php?NoTitle,<code>Img</code>;
IB,ShowCite,images/new.png,,,Show IT quote;
Event,ShowCite,click,getITCite.php,<code>result2</code>;
Note the last item ot the pseudo type Event attached to graphic button by name:  the above Text, Img are the name of widgets and result2 is an ID of a DOM element external to the form.
Image 3

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 and it is 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: the function is called with argument form, obviously it needs a local elaboration.

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 combo boxes 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 can have a timeout parameter to allow periodic updating of comments, texts or images:
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 4

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 , so FormGen generates a tag with class fg_PopUp; the form must have the form pseudo type in order to be generate a title row which reacts to the move event and where the cursor style is set move.
At this point the user must include some JavaScript for move the form (the SandBox 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").addEventListener("mousedown", dragStart.bind(null, event, "fg_PopUp"))
}
CSS
.fg_PopUp { 
	background:#E0E0E0;
	box-shadow:10px 10px #BFBFBF;
    max-width: fit-content;
	max-width: -moz-fit-content;
	position: absolute;
}

Note

  1. ^This is one of some form generators (for Autoit, Powershell, B4A,B4J, Julia, OCTAVE/MATLAB and TCL/TK) which can be found in my site.
  2. ^Some functionality requires HTML5 (input type Date).
  3. ^There are some simple styles:
    JavaScript
    .fg_Button {font-size:10pt;width:70px;height:22px;cursor:pointer;margin:0px 3px;
        background:silver;line-height: 1.25;}
    .fg_Button:hover {background-color: #eee;cursor:pointer;}
    .fg_Button:disabled {cursor: not-allowed;}
    .fg_Comment {padding:3px;}
    .fg_Erase {cursor:pointer;color:#888}
    .fg_Error {color:red;padding:3px;}
    .fg_Label {text-align: right;padding: 3px;}
    .fg_Label:after {content:":";}
    .fg_Separator {text-align:center;padding:3px;}
    .fg_Table {padding-top:5px;margin: 0 auto;}
    .fg_Table td, th {border: 1px solid #900}
    .fg_Table td {font: normal 10pt Arial;padding:2px 1px}

History

  • 15th January, 2024: Initial version

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 
This is a great inspiring article. I am pretty much pleased with your good work. You put really very helpful information. Keep it up once again.
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 
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.