Dynamically Add HTML Form Elements

30 November -0001
November 15, 2005

Recently I have been toying with the idea of reworking some online e-mail solutions and I ran across a recurrent user complaints about file upload attachments. Basically the typical web based e-mail interface includes a couple of places for attachments, but usually doesn't allow the user to determine how many attachments they would like to upload. I thought about this for a while and decided that the best solution would be to allow the users to optionally add as many (or as few) form fields necessary to upload the file. The kicker, as I explored the system, turned out to be a trick whereby the user could add new form fields while still retaining the values of existing fields. My first attempts were simply rewriting div elements and adding new innerhtml to the div for each requested form field. This solution worked, but it rewrote the entire div, thereby removing any pre-filled form elements. It turned out that by writing new divs to the page and putting the new form element in a unique div. Special thanks to Dustin Diaz for the javascript to enable the dynamic div creation.

<html>
<head>
<script type='text/javascript'>
	function addArea() {
		var newArea = addElement();
		//var area = document.getElementById('area').innerHTML;
		var area = "<input type='file' name='attachment[]'/>";
		document.getElementById(newArea).innerHTML = area;
	}
	function addElement() {
		  var ni = document.getElementById('area');
		  var numi = document.getElementById('intVal');
		  var num = (document.getElementById('intVal').value -1)+ 2;
		  numi.value = num;
		  var newdiv = document.createElement('div');
		  var divIdName = 'my'+num+'Div';
		  newdiv.setAttribute('id',divIdName);
		  ni.appendChild(newdiv);
		  return divIdName;
	}
</script>
<body>
<form method='post' action='dynwrite_scr.php'>
<div id='area'></div>

<br/>
<a onclick='addArea()' href='#'>add</a>
<br/>
<input type='hidden' value='0' id='intVal'/>
<input type='submit'/>
</form>
</body>