views:

32

answers:

2

When a user selects a file, I want another file field to appear. It works for the first file, but if i choose a file in the second field, it doesn't get 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>
+1  A: 

When you write $(...).change(function), you are adding the handler to the elements that are currently in the jQuery object. When you add a new <input>, it doesn;t have any event handlers.

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

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

Note that the selector is only evaluated once, so it won't pick up changes in i.
Instead, you should use :last.

SLaks
Ok that worked. It only worked once i used input:file:last...plus it's a much simpler solution. Thank you.
Catfish
A: 

Since this code only runs when your page is loaded, your onchange handler only applies to an input element with the name uploadedFile0. You need to extend your event handler to create a new element and bind the appropriate event handling function to it.

vezult