...

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



mesh2005
06-14-2007, 11:02 PM
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:
http://www.dustindiaz.com/add-and-re...th-javascript/
Please help.
Thank you

glenngv
06-14-2007, 11:10 PM
You need to show us your code.

mesh2005
06-14-2007, 11:21 PM
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">
<head>
<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.setAttribute("id",divIdName);
newdiv.innerHTML = "File: <input type='file' id='myfile[] name='myfile[]'> <a href=\"javascript:;\" onclick=\"removeEvent(\'"+divIdName+"\')\">Remove</a>";
ni.appendChild(newdiv);
}

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


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

//-->
</script>
</head>

<body>
<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'>
</form>
</body>
</html>

glenngv
06-14-2007, 11:29 PM
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>";

mesh2005
06-14-2007, 11:43 PM
That didn't work too, I still get nothing when the script is posted.

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

enctype="multipart/form-data"



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum