Insert Form Fields On Demand
Hiding and revealing content within div tags is often a practical method of displaying only the form fields a user requires. In some situations, however, the number of fields that might be needed is not readily predictable.
Let's take a gift request list as an example. Some users may require only one form field. Others five. And another might require several dozen. Or even a hundred.
Form fields sufficient for the largest conceivable requirement might be coded into hidden divs to be displayed as needed. And hope there won't be exceptions. It would be a lot of coding, all of which the browser has to load and process.
There is another way. Create the form fields on demand, as few and as many as needed.
Insert Form Fields Example
Let's use the previously mentioned gift request list as a working form example.
It is composed of two parts, JavaScript and a form.
First, let's put the JavaScript into the web page. It doesn't matter whether it is in the HEAD or BODY area. For the example, let's have both JavaScript and form near each other in the source code.
<script type="text/javascript"> // Copyright 2008 Bontrager Connection, LLC // https://www.willmaster.com/ // When no form field name is provided, it is assumed // to be the default name with the default name // increment number appended. var DefaultName = "gift"; var DefaultNameIncrementNumber = 0; // No further customizations required. function AddFormField(id,type,name,value,tag) { if(! document.getElementById && document.createElement) { return; } var inhere = document.getElementById(id); var formfield = document.createElement("input"); if(name.length < 1) { DefaultNameIncrementNumber++; name = String(DefaultName + DefaultNameIncrementNumber); } formfield.name = name; formfield.type = type; formfield.value = value; if(tag.length > 0) { var thetag = document.createElement(tag); thetag.appendChild(formfield); inhere.appendChild(thetag); } else { inhere.appendChild(formfield); } } // function AddFormField() </script>
The JavaScript will work "as is" for the gift list form example. It can be modified for other uses (see "Notes About The Form Field Insertion JavaScript" further below).
For the example, no edits need to be made to the JavaScript.
Here is the example form:
<form> <table border="0"><tr><td align="right"> Name: <input name="name"><br /> Email: <input name="email"> </td></tr></table> List gifts, one per field. If another field is needed, click the "[more]" link. <div id="inhere"> <input type="text" name="gift"> </div> <a href="javascript:AddFormField('inhere','text','','','div')">[more]</a> <br /> <input type="submit"> </form>
Paste the form into the test web page with the JavaScript. It will work as is.
Before talking about how it works, here is a working example.