View Full Version : How to add file input dynamically to the form?

06-15-2007, 12:02 AM
I found an article about a simliar topic but I had two problems:
First: the created file input items were not posted to my server, I printed the $_FILES and I found nothing. Is that normal for dynamic HTML controls?
Second: I tried to validate the file input items using javascript but I failed to reference the dynamic items. I tried using getElementByID and getElementByName but they didn't work too.
Here is the article:
Please help.
Thank you

06-15-2007, 12:10 AM
You need to show us your code.

06-15-2007, 12:21 AM
Here is the code I use:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Add/Remove child: Javascript</title>
<script type="text/javascript">

function addEvent()
var ni = document.getElementById('myDiv');
var numi = document.getElementById('theValue');
var num = (document.getElementById("theValue").value -1)+ 2;
numi.value = num;
var divIdName = "my"+num+"Div";
var newdiv = document.createElement('div');
newdiv.innerHTML = "File: <input type='file' id='myfile[] name='myfile[]'> <a href=\"javascript:;\" onclick=\"removeEvent(\'"+divIdName+"\')\">Remove</a>";

function removeEvent(divNum)
var d = document.getElementById('myDiv');
var olddiv = document.getElementById(divNum);
var numi = document.getElementById('theValue');
numi.value = numi.value - 1;

function validate ()
//alert ('hi');
//var ni = document.getElementById('myfile');
return true;


<form method='post' action='js3_action.php' name='form1' onsubmit='return validate()'>
<input type="hidden" value="0" id="theValue" name='theValue'/>
<p><a href="javascript:;" onclick="addEvent();">Add Some Elements</a></p>
<div id="myDiv"> <script type="text/javascript">addEvent(); </script></div>
<input type='submit' name='submit'>

06-15-2007, 12:29 AM
You missed the closing quote in the id attribute causing the name attribute to be part of the id value. So you were submitting a field with no name.

newdiv.innerHTML = "File: <input type='file' id='myfile[]' name='myfile[]'> <a href=\"javascript:;\" onclick=\"removeEvent(\'"+divIdName+"\')\">Remove</a>";

06-15-2007, 12:43 AM
That didn't work too, I still get nothing when the script is posted.

06-15-2007, 01:00 AM
The <form tag needs the following parameter in order for file uploads to work -