开发者

[jquery]How do I add file uploads dynamically?

开发者 https://www.devze.com 2023-02-02 16:40 出处:网络
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

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?


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.


You could try something like this.

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

精彩评论

暂无评论...
验证码 换一张
取 消