Adding file input to a form using jQuery

I am new to jQuery and I am trying to make a simple HTML loading page and I want to add a new file to create after selecting some file. I tried this code

<form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();"> <label for="file">Soubor:</label> <input type="file" name="files[]" id="file" /><br /> <input type="submit" name="Odeslat" value="Odeslat soubor" /> </form></body> <script> $('#upload').delegate('input[type=file]', 'change', function(){ alert('Alert'); addField(); }); </script> 

and this addField () function

 function addField(){ $('<input type="file" name="files[]" id="file" /><br />').insertAfter('#file'); }; 

But if I run this code, the third input field will be inserted after the first, and not after the last field. Is it possible to add input fields after the last file entry without using unique identifiers for these inputs? http://jsfiddle.net/aHrTd/

Thanks for any help.

+4
source share
4 answers

How about this - (find the last input:file in the form and insert a new input after it)

 function addField(){ $('form input:file').last().after($('<input type="file" name="files[]" class="file" /><br />')); } 
+7
source

Here is the solution: http://jsfiddle.net/aHrTd/4/

Adds a unique name and identifier to the new input files and inserts them after the last input of the file, as pXL suggested.

Please note that I used one of the most poorly used jQuery functions, although it is easy to find ( http://api.jquery.com/jQuery/ ) you can build a new element for you in its purest form.

 <form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();"> <label for="file">Soubor:</label> <input type="file" name="files" id="file" /><br /> <input type="submit" name="Odeslat" value="Odeslat soubor" /> </form> <script> function addField(){ var lastfile = $('form input:file').last(); var countfile = ($('form input:file').length)+1; $( "<input/>", { "type": "file", "name": "file_"+countfile, "id": "file_"+countfile }).insertAfter(lastfile); fileinputmonitor(); } function fileinputmonitor(){ $('input[type="file"]').change(function(){ alert('Alert'); addField(); }); } fileinputmonitor(); </script> 
+2
source

Your input must have unique identifiers. Give them a unique identifier and it should work fine.

0
source

You can use . last ()

HTML

 <form id="upload" action="upload.php" method="POST" enctype="multipart/form-data" onchange="addField();"> <label for="file">Soubor:</label> <input type="file" name="files[]" id="file" class='dynamic-file' /><br /> <input type="submit" name="Odeslat" value="Odeslat soubor" /> 

Js

 function addField(){ $('<input type="file" name="files[]" class="dynamic-file" /><br />').insertAfter($('.dynamic-file').last()); }; 
0
source

Source: https://habr.com/ru/post/1487150/


All Articles