Forwarding Forwarding - 1 month ago 5
jQuery Question

How to have the user add another upload input by clicking?

I've been using this:


http://plugins.krajee.com/file-basic-usage-demo


It's a file upload widget, and I'd like to know how I can make this so that a user can click a button and generate another file upload input (but with a hidden limit of, say, 10). So, say, I have the following:

<div class="form-group row">
<label for="file1_recipient" class="col-xs-2 col-form-label">Upload Photo (1)</label>
<div class="col-xs-10">
<input id="file1_recipient" type="file" class="file">
</div>
</div>


And I want to the user to click and get:

<div class="form-group row">
<label for="file1_recipient" class="col-xs-2 col-form-label">Upload Photo (1)</label>
<div class="col-xs-10">
<input id="file1_recipient" type="file" class="file">
</div>
</div>

<div class="form-group row">
<label for="file2_recipient" class="col-xs-2 col-form-label">Upload Photo (2)</label>
<div class="col-xs-10">
<input id="file2_recipient" type="file" class="file">
</div>
</div>


And if they click again they'd get three, and so on until 10. How can this be done?

Answer

id of element in document should be unique. You can remove id from initial <input type="file"> element, use .clone(), .last(), .insertAfter() to create a clone of original element and append cloned element to document after last .form-group element. You can create a variable, for example var limit = 10. When 10 clicks are registered set button disabled attribute to "disabled", call .off("click") at button. You can use .text(function), .replace() to increment the digit within parenthesis of cloned <label> element with current + 1, where current is the variable incremented until from 0 until limit:10 is reached at click event handler.

$(function() {
  var limit = 10;
  var current = 0;
  $("button").on("click", function() {
    if (++current < limit) {
      $(".form-group").last().clone()
      .find("label")
      .text(function(_, text) {
        return text.replace(/\d+/, current + 1)
      })
      .end()
      .insertAfter(".form-group:last");
    } else {
      $(this).off("click").prop("disabled", "disabled");
    }
  });
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>Add File</button>
<div class="form-group row">
  <label for="file1_recipient" class="col-xs-2 col-form-label">Upload Photo (1)</label>
  <div class="col-xs-10">
    <input type="file" class="file">
  </div>
</div>