Site Moved

This site has been moved to a new location - Bin-Blog. All new post will appear at the new location.

Bin-Blog

Dynamic Form Field Generation in JavaScript

Ever had the need to create more fields dynamically? For example, consider a form where there is five file uplaod fields. But if the user wants to upload more than five files, they have to upload 5 files first, then come back to that page and agian upload more file. This process would be made much easier if you had added a button that will dynamically add more fields to the form.

The below code will insert more text fields into a form that already has 5 fields in two different categories. I am using a list here - but that is not necessary - you can do it with just a div element.

Codes...

JavaScript Code

//Add more fields dynamically.
function addField(field,area,limit) {
 if(!document.getElementById) return; //Prevent older browsers from getting any further.
 var field_area = document.getElementById(area);
 var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.
 //Find the count of the last element of the list. It will be in the format '<field><number>'. If the 
 //  field given in the argument is 'friend_' the last id will be 'friend_4'.
 var last_item = all_inputs.length - 1;
 var last = all_inputs[last_item].id;
 var count = Number(last.split("_")[1]) + 1;
 
 //If the maximum number of elements have been reached, exit the function.
 //  If the given limit is lower than 0, infinite number of fields can be created.
 if(count > limit && limit > 0) return;
  
 if(document.createElement) { //W3C Dom method.
  var li = document.createElement("li");
  var input = document.createElement("input");
  input.id = field+count;
  input.name = field+count;
  input.type = "text"; //Type of field - can be any valid input type like text,file,checkbox etc.
  li.appendChild(input);
  field_area.appendChild(li);
 } else { //Older Method
  field_area.innerHTML += "<li><input name='"+(field+count)+"' id='"+(field+count)+"' type='text' /></li>";
 }
}

HTML Code

<form name="frm" method="POST">
<strong>Friends List</strong><br />
<ol id="friends_area">
<li><input type="text" name="friend_1" id="friend_1" /></li>
<li><input type="text" name="friend_2" id="friend_2" /></li>
<li><input type="text" name="friend_3" id="friend_3" /></li>
<li><input type="text" name="friend_4" id="friend_4" /></li>
<li><input type="text" name="friend_5" id="friend_5" /></li>
</ol>
<input type="button" value="Add Friend Field" onclick="addField('friends_area','friend_',10);" />

<strong>Enemies List</strong><br />
<ol id="enemies_area">
<li><input type="text" name="enemy_1" id="enemy_1" /></li>
<li><input type="text" name="enemy_2" id="enemy_2" /></li>
<li><input type="text" name="enemy_3" id="enemy_3" /></li>
<li><input type="text" name="enemy_4" id="enemy_4" /></li>
<li><input type="text" name="enemy_5" id="enemy_5" /></li>
</ol>
<input type="button" value="Add Friend Field" onclick="addField('enemies_area','enemy_',0);" />
</form>

Demo

I have created a Demo of this example in my site.

See Also

Peter Paul Kosh's Extending forms.

35 Comments:

Anonymous said...

This comment is unrelated to your post. Your nav bar on the left. It's what I would call broken, others would call it limited.
I tested it in Firefox, IE and Opera. It only worked properly in Firefox. In IE it places itself too far right. In Opera it only opens the submenus when hovering over the actual link, not the box.
I think you should be able to fix it.

Binny V A said...

Thanks for letting me know - I will fix it as soon as possible.

I never noticed this issue - I always use Firefox to browse the net.

Aakash said...

hi binny,

I am looking for this kind of functionality. But here I wanted to add two different fields at the click of a button. one field is list of dynamic data(thru database). But the data in list would be same for all fields. Is it possible through client side script. OR a server side in this asp, can only do this?

Anonymous said...

Thsnks for the sample demo. I found it very useful and am implementing it on my website.

Anonymous said...

I want to add three fields (next to each other) when the button is clicked. field1 field2 field3, but right now when I click the button it is only creating field 1, down and down and down, can I have it create multple fields across, following the same naming convention?

field1_1 field2_2 field3_2

Binny V A said...

@Me
Just use CSS to style the elements to appear whatever way you choose. In the example, you can make it happen by using this style
#friends_area li {
display:inline;
}

Anonymous said...

Have you provided an option to remove the elements? Also, what if I want to preserve the contents of the input field, especially if I leave the page and decide to go back to it?

Unknown said...
This comment has been removed by the author.
Anonymous said...

is the script server specific? coz when i copy it onto my server it does not work (same thing happens with Koch's script http://www.quirksmode.org/dom/domform.html). can u tell me what exactly is missing on my server that this method doesnt work? is DOM something that has to be installed (i thought it was the browser that was responsible for handling it)?

Binny V A said...

@deff
There is nothing server specific in this JavaScript code. DOM is handled by the Browser. However, some server will insert some code into the pages they serve - this is true of the free hosting providers like Geocites, tripod etc. If their code has an error, it might prevent the proper functioning of your code.

Anonymous said...

hi, your post has been very informative and helpful! i was wondering, what kind of license does your tutorial code carry?

Binny V A said...

@Anonymous
All the code in the site is in BSD License

Anonymous said...

Wow, I was afraid you wouldn't see my comment to this 1 year old article. Thanks for the quick reply! :)

Anonymous said...

run your code and it gave me following error message:

"null" is null or not an object:

var field_area = document.getElementById(area);
var all_inputs = field_area.getElementsByTagName("input"); //Get all the input fields in the given area.

Anonymous said...

The js code on this page is wrong. That is why you are getting a null. it needs to be this.

Go to the Demo and do a view source. The function parameters are not in the right order. It needs to be this.
function addField(area,field,limit)

Thanks,
-toe

Anonymous said...

Thanks, it will be very useful to me.

Anonymous said...

IS it possible to use your form and do a HTTP Post which will create a CSV file?

SmartAtHome said...

Is it possible to remove text fiels again with an extension to this script?

Binny V A said...

@Pieter Thoma
Yeah - thats possible - you just have to code it.

Anonymous said...

how do you get it to work with "select" boxes vs. a standard input box? i tried replacing some of the input tags with select tags in the JS, but it fails in IE.

SmartAtHome said...

This does the trick:

http://www.trans4mind.com/personal_development/JavaScript2/createSelectDynamically.htm

Anonymous said...

Good example. I am using jsp. It works fine in IE. When I run in firefox, I can not get the value or field name added dynamically by using the javascript.

what I used is request.getParameterNames() ;

how did you handle this in your case?

Thanks

Digital Jedi said...

Is it possible to use this method to create more then one field on click? Say, for example I need it to generate an additional name and age field.

Digital Jedi said...

I meant to append this to my last question, but I also wanted to ask if it where possible to add length to the additional fields. Been experimenting, but haven't gotten one to work yet.

Anonymous said...

In the code "sample"

This line is wrong

function addField(field,area,limit) {

It should b

function addField(area,field,limit) {

Anonymous said...

Thanks for the code.
I tried to use it with "div" area instead of list and also to add a "select" element instead of input. But didn't work for me. Any idea if we can make the code work with select element or not ?

Anonymous said...

Thanks for the code.
I tried to use it with div area and select element instead of input. But didn't work. Any idea if/how we can make the code work with select element. TIA
@s

Curtis said...

Binny - I used this and it works, however it appears to break "POST" functionality. I can only retrieve my form data using the $_GET global. Is there an easy way to fix this? Or am I doing something wrong? I have method="POST" but it seems dynamically adding fields messes POST up.

Thx.

Curtis

Anonymous said...

very thanks, but there are one mistake in the code "field" instead "area", in the line 7:
var field_area = document.getElementById(field);
instead of:
var field_area = document.getElementById(area);

Best Regards,
Nazih AL-Maarri

humble said...

That is perfect. But I want so see the code that could add more than one field in a click.
For instance, in case of education, an user can fill the form as he desire. The form field are : Degree Name, Board, University Name and Percentage.

So when ever an user click in add more button the above form filed should be displayed at once.
Can you please suggest me in this case.

Unknown said...

Hi Binny, this code example has been very informative. How do you capture the form elements once they are submitted? I am using PHP and MySQL and am stumped as to how to grab the innerHTML generated form elements.

Anonymous said...

I saw these bugs:

If you try to REMOVE all fields from the Add Neutral Field.

You can't add anymore.

If you try to save but 1 Field from The Add Neutral Field, and then Add a New One, the New One won't have the option or link to "Remove Field"

Anonymous said...

What is the specific code to add multiple fields field 1, field 2, field 3 on the same line when you click the add button ? Also what is the code to add cell spacing between the fields ?
Thx !

Ancy kottakkal said...

hi..plz help me in generating fields dynamically..also that field hav to get stored in database..plz help me..as i'm new to php..actually i want form of name,email,phone,required field.then wen running user can specify field as his requirement..also tat field value must get save into database...plz can u post code for tat..hop u understand..

Anonymous said...

Hai..Good Ahternoon Binny...I had seen your demo..Iam searching for this type program bt i have a small problem in it.how to insert these fileds into a database...please solve this..Thanking You