James123
James123

Reputation: 11652

input type file OnChange not able to get filename in jquery?

I am trying to get file name from input type='file' OnChange and after that. it is if giving length equal to 1. But val() is empty. How get file name here?

<span class="btn btn-primary fileinput-button">
   <i class="glyphicon glyphicon-plus"></i>
   <span>@(i18n_Models_Image.AddImages + "...")</span>
   <input id="fileupload" type="file" name="files[]" accept="image/*">    
</span>

$('#fileupload').on('change', function(e) {
   console.log("hi");
   console.log($('#fileupload').val()); // is empty
});

Upvotes: 1

Views: 3539

Answers (1)

AmanVirdi
AmanVirdi

Reputation: 1685

Check if you have included the jquery file which supports the .on(). (i.e jQuery 1.7 or greater)

And ensure that you have added your code into the document.ready or window.load.

$(document).ready(function() {
   $('#fileupload').on('change', function(e) {
      console.log("hi");
      console.log($('#fileupload').val()); // is empty
   });
});

To get file name try the following:

var filename = $('#fileupload').val().split('\\').pop();

Or

var filename = $('#fileupload').val().replace(/C:\\fakepath\\/i, '');

Working fiddle is here

Upvotes: 1

Related Questions