In the following article, I'm going to show you how to dynamically create new HTML input fields using Javascript Document Object Model.
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"> <tr id="new_file_row"> <td> <input type="file" name="new_file[0]" id="new_file[0]" readonly="readonly" onchange="add_new_file(this)" /> </td> </tr> </table> </form> |
The HTML form would initially contain only one file upload input field. The next step would be implementing the Javascript function that dynamically append a new file upload field to the form when this one is used.
Step 2 - Javascript function to a add a new file upload field:
function add_new_file(field) |
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.
Step 3 - Javascript function to delete previously uploaded files:
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. control.parentNode.removeChild(control); } |
Finally, the last step would be implementing a function to delete the uploaded file when the Delete button is clicked.