Get all values of multiple file select with jQuery

2019-04-07 18:09发布

问题:

Possible Duplicate:
Retrieving file names out of a multi-file upload control with javascript

Got this:

<input type="file" name="file1" multiple="multiple" />

Using this in jQuery:

$("input[name=file1]").change(function() {
    $("input[name=file]").val($("input[name=file1]").val());
});

Now my problem is this: It only gives the first selected file, I would like to have them all... How to do this? Thanks!

回答1:

Although I linked to a possible dupe in the comments, it's a pure JavaScript solution. Here's a jQuery version if you like: jsFiddle example

$("input[name=file1]").change(function() {
    var names = [];
    for (var i = 0; i < $(this).get(0).files.length; ++i) {
        names.push($(this).get(0).files[i].name);
    }
    $("input[name=file]").val(names);
});​


回答2:

You are looking for the 'files' property, which returns a filelist:

var ele = document.getElementById($(this).attr('id'));
var result = ele.files;

Here is the Fiddle for it



回答3:

Use .length() to get the number of files then use a while statement to do the same for all files, increasing the count by 1 each time :)