Read value input type file doubt

7

One question, why does it work:

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

And that's not it?

$("input[type='file']").files[0] // TypeError: $(...).files is undefined
    
asked by anonymous 01.10.2015 / 16:03

4 answers

9

With Wallace responding, it returns a jQuery Object . That way, you're accessing the first (and probably only, in your case) DOM element that returned the object.

You can access an element, as follows:

$("input[type='file']")[0]

or

$("input[type='file']").get(0)

There is also the function .first () , which will return the first DOM element of the object returned by the selector:

$("input[type='file']").first()

NOTE: The .first () function will create a new jQuery Object with the first element.

@edit

As the hint commented on by the Guilherme Lautert , you can also access an index using the : eq () :

$("input[type='file']:eq(0)")
    
01.10.2015 / 16:50
4

When you do this $("input[type='file']")[0] , you are accessing the HTMLInputElement object, which is native to javascript.

In this element, there is the files property.

Example:

HTMLInputElement.prototype.hasOwnProperty('files'); // true

In the case of $("input[type='file']") you are returning the instance of the jQuery object, which does not have this property.

    
01.10.2015 / 16:49
3

Because JQuery will search for A or + instances of input[type='file'] , then it will list the results in an Object ([0][1][2],etc) .

    
01.10.2015 / 16:16
3

Basically the same answer as Wallace, however I'll explain in a different way.

.files is a native property of the JavaScript DOM API, so it will be accessible only when you use document.getElementById and document.querySelector , for example:

document.querySelector("input[type=file]").files

When you do this:

$("input[type=file]")[0] //ou .get(0)

You transform (extract) an object to DOM as if get caught with document.querySelector , making .files accessible.

Then .files would only be accessible as $(...).files if this property existed in jQuery.

  

Note: document.getElementsByName , document.getElementsByTagName and document.querySelectAll returns objects arrays then .files is only available if you access one of this array .

There is a way to make this accessible, using jQuery.fn. of jQuery, it would look like this:

jQuery.fn.extend({
    "files": function() {
         var el    = this.get(0);
         var files = el ? el.files : false;
         return files ? files : [];
    }
});

And using it should be something like:

console.log($("input[type=file]").files());

Note that it will return a array with the selected files and only the first element of the "jQuery object" list.

    
07.10.2015 / 23:35