0

I want to get the filename of a file user selected when a user clicks on a button it is not a submit button. I have tried many of the solutions given on stackoverflow but it does not work i have id of the field but it does not give the name of the file.

Below is my code:

function Data(a)
{   
var ext = $('#fieldid_'+a).val().split('.').pop().toLowerCase();
.......

<input type="file" name="save_<?=$row1['id']?>" id="fieldid_<?=$row1['id']?>" /> 
<input type="button" id="submit_<?=$row1['id']?>" value="Upload File" onclick = "return Data(<?=$row1['id']?>)"/> 
user3653474
  • 2,035
  • 1
  • 24
  • 57
  • What does it give you? Pop removes the last element from the array so you are grabbing the extension of the file. – epascarello Oct 29 '15 at 12:50
  • @epascarello blank value, i have also checked it with $('#fieldid_'+a).val() but the same blank value is the output. – user3653474 Oct 29 '15 at 12:51
  • So I ran the code with no issues, it returns the extension. So time to debug. What does `console.log( $('#fieldid_'+a));` return? My guess it is empty meaning it is not finding the element. – epascarello Oct 29 '15 at 12:54
  • Please put the generated source code and not the php mark up in your question. There is something wrong with selecting the element. – epascarello Oct 29 '15 at 13:04

3 Answers3

1

Use the below script to get the file name: Reference Link:Use jQuery to get the file input's selected filename without the path

jQuery('input[type=file]')[0].files[0].name

(OR)

$('input[type=file]')[0].files[0].name

For more than on file:

var all_files = jQuery('input[type=file]');
var paths_arr = [];
for(var i=0;i<all_files.length;i++){
paths_arr.push(all_files[i].files[0].name);
} 
 paths_arr[0] = first file name
 paths_arr[1] = second file name
Community
  • 1
  • 1
Ananthakumar
  • 323
  • 1
  • 14
0

Files is the FileList object & names is an Array of strings (file names)

$( "#buttonid_1" ).click(function(){
    var files = $('#fieldid_1').prop("files");
    var names = $.map(files, function(val){
        return val.name;
    });
    console.log(names[0]);
})

Reference: https://stackoverflow.com/a/10703223/3119231

Example: http://jsfiddle.net/ndfn782o/1/

EDIT: tested && 110% working

Community
  • 1
  • 1
0
document.getElementById('fileInputId').files[0].name

see fiddle

Romko
  • 1,623
  • 19
  • 25
  • This didn't work. It is giving following error Uncaught TypeError: Cannot read property 'files' of null – user3653474 Oct 29 '15 at 12:59
  • "How to get the filename from file input type with jquery without form submit" –  Oct 29 '15 at 13:04