1. Computing

Dynamic JavaScript Forms Tutorial

From , former About.com Guide

2 of 5

Page Two

Form.prototype.addInput = function(tx, l, n, v, st) {

We don't know in creating our form object just what particular form fields that a given form will need to contain so what we will do is to add separate methods for adding each of the different types of field that we might need. This code adds a method called addInput to our Form object.


switch(tx) {
case 'text': case 'radio': case 'checkbox': case 'submit': case 'button':

What we need for all the different types of input tag differ depending on the type so we start by checking what type of input field we are creating (by using a switch statement rather than a series of if statements since the switch statement is shorter).


var d = document.createElement("div");
var t = document.createTextNode(l + ' ');
var lab = document.createElement("label");
lab.appendChild(t);

For each of the input tags we are currently looking at we'll need a label to tell people what to input. Ideally we'll want the label and the input field on the same line separated from the other inputs so we'll wrap the whole thing inside a div tag to make it easier. Creating the textnode to go inside the label tag and adding that into the label reuses the same sort of statements as we already used to add the legend text into the legend tag.

©2013 About.com. All rights reserved.