Galactic Civilizations 3
Dynamic form in JavaScript

Dynamic form in JavaScript

Category: Javascript.
Posted by on the 18/07/2013.
Last update on the 18/07/2013.


This tutorial explains how to create a dynamic form in JavaScript.


This tutorial explains how to add/remove fields in a form in JavaScript. This tutorial can be realized with a simple text editor like « Notepad ». This tutorial requires some basic knowledge in HTML and JavaScript.

HTML form

First of all, create a file and name it dynamic-form.html.


<form name="dynamicForm">
   <input type="button" onclick="add(this);" value="add a field"/>
   <br /><br />
   <input type="submit" value="submit"/>

As you can see, this form is very simple. The name of the form is « dynamicForm ». It contains a button that allows adding new fields.

This button listen the onclick event and call the JavaScript function « add(Element) » that allows to add a new field above the button « add a field ».

Add function

Now, we will write the JavaScript function that allows adding new fields inside the form. To do that, add the following code above the form:


<script type="text/Javascript" >
   function add(element){
     var form = window.document.dynamicForm;
     // We clone the add button
     var add = element.cloneNode(true);
     // Create a new HTML tag of type "input"
     var field = document.createElement("input");
     // The value filled in the form will be stored in an array = "champs[]";
     field.type = "text";
     var rem = document.createElement("input");
     rem.value = "Remove a field";
     rem.type = "button";
     // Add the onclick event
     rem.onclick = function onclick(event)
     // We create a new element of type "p" and we insert the field inside.
     var bloc = document.createElement("p");
     form.insertBefore(add, element);
     form.insertBefore(rem, element);
     form.insertBefore(bloc, element);

As you can see, the add function inserts two buttons (add and remove field) before the element that call the function. Furthermore, it puts the field in a « p » tag and adds this HTML tag after the two buttons.

Delete function

The delete function is simpler because it just removes the three elements from the form: the add button, the delete button and the « p » block. Here is the code of the delete function to copy between the « script » HTML tags:


function delete(element){
   var form = window.document.dynamicForm;
   // Remove the add button
   // Remove the field
   // Remove the delete button

We have finished the development of our dynamic form.

You like this tutorial ?
Like this website in order to promote it on facebook !

You like this tutorial ? Share it with your friends !
Partager sur Facebook Partager sur Twitter Partager sur Myspace Partager sur Stumbleupon Soumettre sur Reddit Partager sur Digg Ajouter à vos favoris Technorati Ajouter à vos favoris Live Ajouter à vos favoris Google Ajouter sur vos favoris Yahoo