Thursday, April 28, 2011

How to use jQuery to get the current value of a file input field

From what I've ready you should be able to use the 'value' property of a file input field to get the currently set path of that field. But when I do this:

 $('#fileinput').value()

I get 'undefined'. The ID of the field is set to "fileinput" I'm sure. Does anyone have any thoughts on why this might not be working for me?

And by the way, this works:

var d = document.getElementById('AttachmentFile');
alert(d.value);

So I guess this has something to do with the way jQuery works that I don't fully understand.

Thanks!

From stackoverflow
  • You need to use val rather than value.

    $("#fileinput").val();
    
    Jan : This works in Firefox but not in Google chrome :(
  • I don't think there is any real legitimate way to access this via the DOM. It would be a security risk that browsers have of late locked down on to prevent drive-by uploads.

    Karim : I think the security risk would be *setting* this value, not reading it.
    Daniel A. White : It would all depend on the browser.
    Will : Having just tested it you get different results depending on where you're running from. Running the file locally you get a full path, running from a webserver you just get the name of the selected file, which makes sense from a security point of view.
  • I think it should be

     $('#fileinput').val();
    
  • its not .val() if you want to get file /home/user/default.png it will get with .val() just default.png

  • Could you also do

    $(input[type=file]).val()

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.