What I'll be demonstarting below is how to use this technique to dynamically add a new file upload field to a form each time the existing file upload field is used. Also, we will be allowing users to remove the files they have previously added.
Step 1 - The HTML page:
| <form method="POST" enctype="multipart/form-data">|
<input type="hidden" name="file_count" id="file_count" value="0" />
<table id="files_table" border="0" cellpadding="0" cellspacing="0">
<input type="file" name="new_file" id="new_file" readonly="readonly" onchange="add_new_file(this)" />
Each time the file upload input field in the HTML form is used, this function will hide the row containing the file upload field and create a new empty file upload field to allow the user to upload another file.
However, the existing file upload field has to be preserved; it cannot be removed because it contains the uploaded file path and data. Instead of removing the field, we just hide it and add a new readonly text field with a Delete button next to it to allow the user to remove the uploaded file in a user friendly way.
| function delete_inserted(field)|
// Get the field name.
var name = field.name;
// Extract the file id from the field name.
var id = name.substr(name.indexOf('[') + 1, name.indexOf(']') - name.indexOf('[') - 1);
// Hide the row displaying the uploaded file name.
document.getElementById("inserted_file["+id+"]").style.display = "none";
// Get a reference to the uploaded file control.
var control = document.getElementById("new_file["+id+"]");
// Remove the new file control.
Finally, the last step would be implementing a function to delete the uploaded file when the Delete button is clicked.