Dynamic JavaScript Forms

Where you want to add forms to your web page that are going to be processed entirely by JavaScript you don't really want the form appearing in the page when JavaScript is unavailable as then the form will be broken. The solution is to dynamically generate the form from JavaScript so that it doesn't appear at all for those visitors who don't have JavaScript enabled. Generating form fields from JavaScript is a little complicated compared to a lot of other JavaScript - particularly because IE8 runs JScript instead of JavaScript and doesn't allow a name to be added to a form field after it has been created. To make the task of dynamically generating forms from JavaScript really easy you can use the "Form" object supplied here to simplify the defining of forms using JavaScript. This latest version has been upgraded both to support IE9+ and to allow you to define optgroups within select lists. Note that the script does not yet support all the new HTML 5 form fields such as combobox.

So first copy the following script and attach it at the bottom of your web page just before the </body> tag.


The first thing we'll need in creating a form from JavaScript is a form tag. To make our form content valid we'll also need to wrap all the form fields inside a container. The fieldset tag exists specifically for this purpose and so we'll use that along with a legend to supply our form with a name. To create these elements to add to our page we simply create a new Form object supplying it with the action, method, enctype, and legend text. To define the form fields you can either add the code you need to the bottom of the above script or alternatively place it in a separate script that you attach after the one above.

var f = new Form('next.php','post','','My Form');

Note that this creates the elements for us, it doesn't actually add it into the web page. We will leave adding it to the page until we have attached all the form fields that we want it to contain so that the form can appear on the page all in one go rather than one piece at a time. For forms that are going to be processed entirely with JavaScript you can leave the first three fields blank.

The simplest fields that we can add to the form are hidden fields. To add a hidden field all we need to do is to specify the name/id we want the field to have and the value. Note that to make things easier the Form object gives all fields the same id as its name except for radio buttons where the ids have numeric suffixes to keep them unique.


For most of the other input field types we can do as HTML does and use the same method to create the same input element. The first parameter we need to specify is the type we want our input field to be with a choice of 'text', 'radio', 'checkbox', 'submit', and 'button'. I have left out 'reset' because reset buttons are seldom used any more since they cause more problems than they solve. I have also left 'file' for a future update to the Form object as I haven't yet decided which way would be easiest to implement it. The second value we need to enter for this method is the label text followed by the name/id,and the default value for the field. A final field contains 'r' to make the field readonly, 'd' to disable it, and 'c' for checkboxes and radio buttons to set which is checked.

f.addInput('text','Your Name','yname','Steve','r');

Each of these creates both the form field itself plus a label for the form field which is positioned to the right of checkboxes and radio buttons and to the left of the other input fields. For the submit button where a label isn't needed we simply leave that parameter blank.

A textarea is another form field type that we may want to include into our form. For this field type we supply six parameters containing the label text, name/id, columns, rows, default content text, and 'r' or 'd' to make it readonly or disabled respectively. While width and height can be overridden from the stylesheet it is usually best to provide them in the HTML.

f.addTextarea('Message','mess',45,3,'some text goes in here','');

The final form field we need to be able to add is a drop down select list. This is the most complex of the form field types we can add. We have five parameters needed to define our dropdown list. The first of these is the label text and the second is the name/id. The third parameter is the number of entries to display. Where this is not supplied or set to 1 and the list only allows one entry to be selected then a regular dropdown list will be displayed. Where this is greater than 1 then that number of entries from the list will be displayed with a scrollbar alongside to allow access to any others. The fourth parameter is where this object gets complicated because the fourth parameter is an array of all the options that you want to add to the select list and each option itself has an array to specify its own parameters. The final parameter for the select is again status flags with 'd' to disable the selection list and 'm' to indicate that multiple selections from the list can be made by holding down the CTRL key.

Coming back to those option arrays we have three entries in the array for each option. The first entry specifies the option text, the second the option value, and the third contains 's' if the option is to be selected by default. If the second and third entries are omitted completely then an optgroup will be created with the supplied text.

f.addSelect('selection', 'mysel', 1, [['group one'], ['first choice - option one', 'oneone', ''], ['first choice - option two', 'onetwo', 's'], ['group two'], ['first choice - option three', 'onethree', ''], ['first choice - option four', 'onefour', '']], 'm');

The final step with all our form fields added (and you can of course add as many of each type as you need) is to attach the form into the web page. To do this we need an element that is already in the page that has an id so that we can specify that id in telling the Form object where to add the form.


The form you just defined will now appear inside of <div id="myform"> or whatever other tag you put the id in that you told the addForm call to add the form into. It can be styled using CSS just as if it were added to the page directly using HTML. Of course none of this has added any JavaScript processing to the form. To do that you simply attach an appropriate event handler to whichever form field it needs to be attached to in order to have it called when that event is triggered These can be inserted anywhere between the call that adds the form field and the one that adds the form to the page. Using event listeners is not required as no other script in the page will know that this form exists and so will not try to add its own processing to the form.

To add an onsubmit event handler you can use any id within the form as the starting point and reference the form from there.

document.getElementById('go').form.onsubmit = function() {return validateForm(document.getElementById('go').form);};

Here's how a slightly rearranged copy of the above form looks (The one change is to move the call to add the submit button to the bottom). Note that the page this form is set to submit to doesn't exist so if you do press the Go button it will take you to the "not found" page for this site.


This article written by Stephen Chapman, Felgall Pty Ltd.

go to top

FaceBook Follow
Twitter Follow