Bluemagica
Bluemagica

Reputation: 5158

[jquery]How do I add file uploads dynamically?

I want to upload multiple files, so I want to add upload fields dynamically through jquery. Now I can do it if I have a button like "add another field", and append the new upload to the form, but I want to do it a bit differently.

Initially the form should have one input field, after the user selects a file to upload I want to immediately add another upload field. Any ideas on how to do this?

Upvotes: 7

Views: 15882

Answers (2)

T.J. Crowder
T.J. Crowder

Reputation: 1074248

The input element has a change event that gets fired when the form field changes. So you can use the event-delegating form of on:

$('selector_for_your_form').on('change', 'input[type=file]', function() {
    var form = $(this).closest('form');
    form.append(/* ... markup for the new field ... */);
});

The change event is actually hooked up to the form, but only fires the handler if the event passed through an element matching the selector input[type=file]. (jQuery ensures that the change event propagates, even in environments where it doesn't by default.)

Live example: (I assume your markup would be a bit more interesting — and certainly better-looking — than shown there)

jQuery(function($) {
  $('form').on('change', 'input[type=file]', function() {
    var form = $(this).closest('form');
    form.append('<input type="file">');
  });
});
  body {
    font-family: sans-serif;
  }
  p {
    margin: 0px;
  }
<form>
  <input type='file'>
</form>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>


Notes:

  • If you need to support obsolete versions of jQuery without on, you can use delegate which is like the delegating form of on but with the arguments in a different order.
  • If you need to support obsolete browsers and obsolete versions of jQuery, the change event may not bubble and older jQuery didn't make it bubble for delegate (even though it did when hooked directly).

In either case, see the 2011 version of this answer (with a minor change to the JSBin links) for examples, etc.

Upvotes: 13

Damiqib
Damiqib

Reputation: 1077

You could try something like this.

<input type="file" name="file" onChange="if ($(this).val() != '' {addNewfileInput();}">

Upvotes: 0

Related Questions