3

I am using bootstrap file input. Its not showing browsed files name for dynamically added file inputs. This is code,

HTML

<div class="container" style="margin-top: 20px;">
<div class="row">
    <div class="col-lg-6 col-sm-6 col-12">
        <div class="fileinputs">
            <div class="input-group">
                <span class="input-group-btn">
                    <span class="btn btn-primary btn-file">
                        Browse&hellip; <input type="file" multiple>
                    </span>
                </span>
                <input type="text" class="form-control" readonly>
            </div><br/>
        </div>
        <a href="#" id="new-btn">Add New</a>
        <div id="new-div"></div>
    </div>
</div>

CSS

.btn-file {


 position: relative;
  overflow: hidden;
}
.btn-file input[type=file] {
  position: absolute;
  top: 0;
  right: 0;
  min-width: 100%;
  min-height: 100%;
  font-size: 100px;
  text-align: right;
  filter: alpha(opacity=0);
  opacity: 0;
  background: red;
  cursor: inherit;
  display: block;
}
input[readonly] {
  background-color: white !important;
  cursor: text !important;
}

JQUERY

$(document).ready( function() {
    $('#new-btn').on('click', function(){
        $('#new-div').append($('.fileinputs').html());
    });

    $('.btn-file :file').on('fileselect', function(event, numFiles, label) {

        var input = $(this).parents('.input-group').find(':text'),
        log = numFiles > 1 ? numFiles + ' files selected' : label;

        if( input.length ) {
            input.val(log);
        } else {
            if( log ) alert(log);
        }

    });
});

$(document).on('change', '.btn-file :file', function() {
      var input = $(this),
          numFiles = input.get(0).files ? input.get(0).files.length : 1,
          label = input.val().replace(/\\/g, '/').replace(/.*\//, '');
      input.trigger('fileselect', [numFiles, label]);
    });

By using this code I can see the file name only on the first file field. For dynamically added file inputs its not working.

This is my jsfiddle. How can I show the browsed file names on corresponding locations ?

1 Answer 1

4

You need to use a delegated event handler to catch your fileselect event as the new file inputs are dynamically appended to the DOM after page load, where the original handler is attached. Try this:

$(document).on('fileselect', '.btn-file :file', function(event, numFiles, label) {
    // your code...
});

Updated fiddle

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.