Add Input Fields Dynamically to Form Using JavaScript

Feb 8th, 2010

Here you will get working code for adding input fields dynamically using a link or button. Default number of input fields are provided and you want to give users a option to add more input elements then this script will work. Be it Input box field, Textarea or any other form elements,  it will work the same way.

I will mention two examples here. One will show adding any single element (Input box in my example) and another will show you how to add set of HTML elements. Combined both, modifying the code for specific usages should not be difficult job.

Example: Add Input Box Dynamically using JavaScript

JavaScript code:

<script type="text/javascript">
function validate(frm)
{
	var ele = frm.elements['feedurl[]'];

	if (! ele.length)
	{
		alert(ele.value);
	}

	for(var i=0; i<ele.length; i++)
	{
		alert(ele[i].value);
	}

	return true;
}

function add_feed()
{
	var div1 = document.createElement('div');

	// Get template data
	div1.innerHTML = document.getElementById('newlinktpl').innerHTML;

	// append to our form, so that template data
	//become part of form
	document.getElementById('newlink').appendChild(div1);

}
</script>

HTML Code:

<style>
   .feed {padding: 5px 0}
</style>

<form method="post" action="new_ele2.php" onsubmit="return validate(this)">

<table>
<tr>
	<td valign=top> Feed URL (s):</td>
	<td valign=top>
		<div id="newlink">
			<div class="feed">
			   <input type="text" name="feedurl[]" value="http://feeds.feedburner.com/satya-weblog/scripting" size="50">
			</div>
		</div>
	</td>
</tr>
</table>

	<p>
		<br>
		<input type="submit" name="submit1">
		<input type="reset" name="reset1">
	</p>

<p id="addnew">
	<a href="javascript:add_feed()">Add New </a>
</p>

</form>

<!-- Template. This whole data will be added directly to working form above -->
<div id="newlinktpl" style="display:none">
	<div class="feed">
	 <input type="text" name="feedurl[]" value=""  size="50">
	</div>
</div>

JavaScript function add_feed() is the function which will add Input element dynamically to the working form after clicking in Add new link. Comments inside the function will describe the working of the function. Javascript function validate() is just to show you how you handle the input elements client-side. Inside HTML code, form will show you what was the actual elements available to users and how users can add more input fields if she wants. Template is the hidden data ready to be added to the main form on demand. All the data inside the div id=newlinktpl will be added to the form.

Screenshot after user has added data and clicked on "Add new" link:
Add Input Element Dynamically using JavaScript

Another Example:

Dynamically creating form elements (set of element) using JavaScript

Now, I will present another example where the script will add set of HTML elements to the default form. Method of adding the set of elements will be same - user will click on the "Add new" button for adding more data to the form. In the set of elements, one is usual Input Box and another is textarea.

Update (25-07-2010): Few developers have taken extra pain and commented here requesting to provide functionality for deleting the newly set of elements. Those developers could not got the benefits as I have taken time to update but new visitors here like you got the benefits. I have added the delete functionality to the script. In the process, I have touched only JavaScript code. Hope I have not destroyed it!

<script>
/*
This script is identical to the above JavaScript function.
*/
var ct = 1;

function new_link()
{
	ct++;
	var div1 = document.createElement('div');
	div1.id = ct;

	// link to delete extended form elements
	var delLink = '<div style="text-align:right;margin-right:65px"><a href="javascript:delIt('+ ct +')">Del</a></div>';

	div1.innerHTML = document.getElementById('newlinktpl').innerHTML + delLink;

	document.getElementById('newlink').appendChild(div1);

}
// function to delete the newly added set of elements
function delIt(eleId)
{
	d = document;

	var ele = d.getElementById(eleId);

	var parentEle = d.getElementById('newlink');

	parentEle.removeChild(ele);

}
</script>

HTML for Dynamically creating form elements:

<style>
   #newlink {width:600px}
</style> 

<form method="post" action="">

<div id="newlink">
<div>
<table border=0>
	<tr>
		<td> Link URL: </td>
		<td> <input type="text" name="linkurl[]" value="http://www.satya-weblog.com"> </td>
	</tr>
	<tr>
		<td> Link Description: </td>
		<td>  <textarea name="linkdesc[]" cols="50" rows="5" ></textarea> </td>
	</tr>
</table>
</div>

</div>
	<p>
		<br>
		<input type="submit" name="submit1">
		<input type="reset" name="reset1">
	</p>

<p id="addnew">
	<a href="javascript:new_link()">Add New </a>
</p>

</form>

<!-- Template -->
<div id="newlinktpl" style="display:none">
<div>
<table border=0>
	<tr>
		<td> Link URL: </td>
		<td> <input type="text" name="linkurl[]" value=""> </td>
	</tr>
	<tr>
		<td> Link Description: </td>
		<td> <textarea name="linkdesc[]" cols="50" rows="5" ></textarea> </td>
	</tr>
</table>
</div>
</div>

Initial Form:

Dynamically add HTML elements to form on click

After Adding one more set of elements:

Screen-shot after user clicked the Add new link

If you like the script and examples for dynamically creating and deleting text Input then help me sharing the word. Share on delicious or digg this. Subscribe to feed to stay up-to date.

Update: Few developers are feeling difficulty in using data submitted through the form this way, so I am adding these line of codes as a hint.

<?php

if(count($_POST))
{

	$len = count($_POST['linkurl']);

	for ($i=0; $i < $len; $i++)
	{
		echo $_POST['linkurl'][$i] . '<br>';
		echo $_POST['linkdesc'][$i] . '<br>';

	}
}

?>

For more on dynamically working with Form elements check here as well: Dynamically Populate Select List by Ajax or check in Related posts section below.
Update: More on Adding Input fields dynamically on quirksmode here.

Share/Bookmark

 

Possibly Related posts:

  • Cmspagnola
    Thank you for this script. It really helped me out with a project I was attempting at work. I was wondering though, do you know how I would be able to get the fields to group themselves together in an email as I have them grouped on my contact form.

    Each time new fields are added, the email simple lists each field one after another, because they are in an array. I want them to group in their designated groups (link url and link description listed one after another in a group, and then the next added fields listed together the same way instead of it being listed like: link url, link url, link description link description.)

    I know there is some sort of merge and sort functions in arrays that could probably do this, but I am fairly new to all of this and don't know how to do it and I can't understand most of the sites that tell me how (nor do I know if this is even what I need). Would there be a way to link the arrays in each group so that they list themselves in an email as they should be?

    If you can't or don't have the time to help, no worries. I simply decided to try here while working through other methods.

    Corinne
  • As I understand you want to group the fields like:
    link1, desc1
    link2, desc2, etc
    So what is the problem! The PHP code mentioned here will output the fields
    like that!
    You can try to add variation to the PHP code. You know that it is in an
    array.
    So, take link and desc at index 1, then at index 2 etc.
  • Nice post, thanks
  • @Kadut
    that functionality I have not written.
    but you can try adding a link on the template and there write add onlick event there - onclick="this.innerHTML=''". So when user click on the link then that part will go.
  • nice article u have here.....

    i want to ask....the script above is work very well, but how to delete field that recently added?
  • kevern jones
    very nice question......I hope Mr. Satya prakash will answer this question, or I hope he will update his script with "Remove" feature......
  • I think you need to try yourself for some time. but I have added few more lines of code. Check for 1st Update at the bottom.
    or try to use any good forum for your doubt.
  • Ashwin Variyar
    Thanks a lot for the quick response......... I used print_r() and used echo with it the data was printed........ but as soon as i inserted in the database the value it showed was "1" whereas the data i intended to insert was "sad".......... the question that i have is how do i insert the data from the form into the database table ??
  • So, what is the problem. Try to use print_r() on your variable which is sending Array to DB.
  • Ashwin Variyar
    I am not able to submit data from the form to a database. I am getting the word Array and not the data...... please help
  • See, I am using add_feed() / new_link() function on "Add New" link. you call any one depending on the type you selected from above code and call that function. Below put that function and replace alert('a').

    <input type="checkbox" name="check1" value="test1" onclick="if(this.checked) alert('a');" >
  • nichico
    can you make it work width a checkbox so when its checked the new imput fields is added?
  • nice post. thanks.
  • zapdude
    well for instance, I want to insert each newly created input field on the form as seperate records in a database table. So the table might be called "linktable" and may have a field named "anewlink", with another primary key setup so that it auto increments.

    So i have changed the form action to point to a PHP script. In this PHP script, I have this line to get the form inputs:

    $feedurl=($_POST['feedurl[]']);

    now i have this line to insert it into the database:

    $sql="INSERT INTO linktable (anewlink) VALUES ('$feedurl')";
    $result1=mysql_query($sql);

    But when i check my table after submitting, it only shows that one blank record has been added, even though i have submitted multiple inputs from the form.

    Could you please give any advice on how to make this work. This would be most appreciated. Thanks
  • Check using $_post['feedurl']. It should give u array
  • kevern jones
    hi, is there any way that we can add remove fields in this form? You reply is very highly appreciated. thanks!
    -kevern
  • Ya, we can do that. but we need to put a remove button/link with each
    section and with that we need to put an id of each section in that
    button/link. So, that we need not determine each time.
  • kevern jones
    Hi Mr. Satya, thanks for this reply... do you have with you the script on this function, im having trouble in adding remove or delete function on may project. Thanks in advance....More power to you!
  • I have added the delete functionality to the script.
  • letmein
    hi, mt satya. GoodDay!

    Thanks for this enhancement, It really helps a lot.
  • Thanks dear! If I could help you then I felt happy. but I do not have the code and I cannot give time to it today. So better you discuss at any forum for speedy solution.
    I see here a great demand for remove functionality, I will keep in mind try to add this as update.
    --
    regards
    Satya
  • zapdude
    Thanks for your reply. Got it working now!
  • whats problem. It is added dynamically in form. If you submit the form then you will see all those elements submitted also.
  • zapdude
    leading on from this, how do I now take the data from the dynamically created input fields and insert them into a mysql database?
blog comments powered by Disqus