1

when I define the file as a variable with jquery selector I get this error : Uncaught TypeError: Array.prototype.map called on null or undefined. if I use :

var file = document.getElementById('file'); 

instead of

var file = $('#file').val();

then it works, but I'm curious why using jquery selector doen't work. Thanks

$('#file').on('change', function(){ var file = $('#file').val(); var sizes = [].map.call(file.files, function(v) {return v.size;}); var totalSize = sizes.reduce(function(a, b) {return a + b;}, 0); }); 
1
  • 1
    i would assume because val is going to give you the string value of the input, not a DomNode which is what getElementById will give you. Commented Feb 19, 2013 at 17:41

2 Answers 2

2

The jquery selector $("#element") returns a jquery object not an actual dom element.

You can test this yourself by opening up the console in chrome or firebug, and selecting an element with jquery.

Also $('file').val() is a function for returning the value of a dom element that has a value attribute.

If you want to use jquery to select but need to manipulate the dom element and not the jquery object, you need to do this:

var file = $('#file')[0]; 

Which will retrieve the dom node from the jquery object.

Sign up to request clarification or add additional context in comments.

1 Comment

@user2014429 yep, been burned by that myself once or twice before. First time I ran into it took me forever to track down why I couldn't do what I wanted.
2

val returns the name of the selected files, you should use files property of the InputElement object.

$('#file').on('change', function(){ var size = 0; $.each(this.files, function(i, v){ size += v.size }) }); 

Please note that IE browsers do not support files property.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.