1

I am working on a file select function. They click a button and the file select window pops up where they can select their file and then upload it. This is working perfectly on a regular html page, but as soon as it is placed within a bootstrap modal the :file function stops working.

I tried searching, but only saw instances where the html5 was not working.

Could there be code for the bootstrap modal be preventing this? It's got me stumped.

//This is simply calling the file select method on the button
$('.attachFile').on('change', ':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]);
});


   //On a regular page this works fine, but within the bootstrap modal this is not being called
    $(':file').on('fileselect', function(event, numFiles, label) {
      console.log('I'm in here!!')
     });

The HTML form looks like this

<form enctype="multipart/form-data">
     <label class="btn btn-primary pull-left attachFile">
        <i class="fa fa-paperclip"></i> Attach
        <input name='media' type="file" style="display: none;">
      </label>
</form>

I am not receiving any errors, just silence. And I cannot breakpoint because it's inline script for the modal. (Not what I would prefer, but that was built before me and I can't change it.)

zazvorniki
  • 3,512
  • 21
  • 74
  • 122

1 Answers1

0

I know it is 1 year and 11 months ago, but I walked into the same issue. And I probably used the same example :) ==> https://stackoverflow.com/a/18164555/2910930

Tested: Bootstrap 4, modal, modal has a form what is filled with ajax.

I used "document" as the main selector, so I am sure it works when events change after that data changed using ajax

ps for those in need of custom triggers https://api.jquery.com/trigger/

// We can watch for our custom `fileselect` event like this
$(function () {

    // Use document instead as the start selector
    $(document).on('fileselect',":file", 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);
      }

    });
});


// We can attach the `fileselect` event to all file inputs on the page
$(document).on('change', ':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]);
});
Bunkerbuster
  • 963
  • 9
  • 17