Search code examples
javascripthtmldomform-fields

trying to generate more file upload fields with unique names using javascript


I've managed to create a button that adds a file upload field, a button that removes a file upload field, and a counter that keeps track of the total number of file upload fields. The problem is that the fields don't seem to have unique names. The fields are supposed to have the names img1, img2, img3, etc... I can see its not working because the files weren't uploaded to the SQL table.

Here's my javascript and HTML:

<script type="text/javascript">
var counter = 0;
function init(){
document.getElementById("counter").value=counter;
}
function add(){
counter++;
if (counter > 10){counter = 10;
}
else{
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+counter>"+"<br>";}
}
function remove(){
counter--;
if (counter <= 0){counter = 0;}
document.getElementById("counter").value=counter;
document.getElementById("addimg").innerHTML="";
for (var i=1;i<=counter;i++)
{
document.getElementById("addimg").innerHTML+="<input type='file' name='img'+i>"+"<br>";
}
}
</script>


<body onLoad = "init()">
<button onClick="add()" >Add Photo</button>
<button onClick="remove()" >Remove a Photo</button><br>
<form method="POST" enctype='multipart/form-data'>
<div id="addimg">
</div>
<input type="text" id="counter" name="counter" value="">
<input type="submit" name="submit" value="submit">
</form>


</body>

Solution

  • See this line:

    document.getElementById("addimg").innerHTML+=
       "<input type='file' name='img'+counter>"+"<br>";}
    

    counter will not be a part of the name

    Use

    document.getElementById("addimg").innerHTML+=
        "<input type='file' name='img"+counter+"' /> <br/>";}
    

    The same misstep in this line:

    document.getElementById("addimg").innerHTML+="<input type='file' name='img'+i>"+"<br>";