Jquery form type = "file" how to determine when a file was selected?

When the user selects a file, I want another file field to appear. It works for the first file, but if I select the file in the second field, it will not be called again. Why not?

jquery script

$(document).ready(function() { var i = 1; $('input:file[name$=\'uploadedFile'+(i-1)+'\']').change(function() { var file = $(this).val(); if(file !== null && file !== "") { $(this).after("<input type=\"file\" name=\"uploadededFile"+i+"\" />"); i++; } }); }); 

html form

 <form action="PHP/file.php" method="post" enctype="multipart/form-data"> <input type="hidden" name="MAX_FILE_SIZE" value="500000" /> <input type="file" name="uploadedFile0" /> <input type="submit" value="SUBMIT" /> </form> 
+4
source share
2 answers

When you write $(...).change(function) , you add a handler to the elements that are currently in the jQuery object. When you add a new <input> , it has no event handlers.

You need to call .live , which will handle the event for all relevant elements no matter when they were created.
For instance:

 $('input:file:last').live('change', function() { ... }); 

Note that the selector is evaluated only once, so it will not receive changes in i .
Instead, you should use :last .

+2
source

Since this code only runs when your page loads, your onchange handler applies only to the input element named uploadedFile0 . You need to expand the event handler to create a new element and associate the corresponding event handling function with it.

0
source

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


All Articles