59

I have a <input type="file" id="uploadPicture" value="123">

When I'm using: alert($("#uploadPicture").val());

It alerts an empty dialog.

Cœur
  • 32,421
  • 21
  • 173
  • 232
Danpe
  • 16,890
  • 19
  • 89
  • 129

8 Answers8

57

@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821
Dmytro Vyprichenko
  • 3,866
  • 2
  • 21
  • 14
47

You can read it, but you can't set it. value="123" will be ignored, so it won't have a value until you click on it and pick a file.

Even then, the value will likely be mangled with something like c:\fakepath\ to keep the details of the user's filesystem private.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
  • 2
    Right -- browsers treat this differently too, for instance firefox will only show the filename after selecting a file, whereas some may show the full path. There is nothing you can really do with this client side.. what are you trying to accomplish OP? – Atticus May 05 '11 at 20:02
10

You can get it by using document.getElementById();

var fileVal=document.getElementById("some Id");
alert(fileVal.value);

will give the value of file,but it gives with fakepath as follows

c:\fakepath\filename
Naresh.P
  • 329
  • 1
  • 3
  • 10
5
$('input[type=file]').val()

That'll get you the file selected.

However, you can't set the value yourself.

Jack Marchetti
  • 15,026
  • 13
  • 73
  • 116
4

You can't set the value of a file input in the markup, like you did with value="123".

This example shows that it really works: http://jsfiddle.net/marcosfromero/7bUba/

marcosfromero
  • 2,853
  • 15
  • 17
2

It's old question but just in case someone bump on this tread...

var input = document.getElementById("your_input");
var file = input.value.split("\\");
var fileName = file[file.length-1];

No need for regex, jQuery....

Bozidar Sikanjic
  • 667
  • 4
  • 12
0

array of files

let files = document.getElementById('your_input_id').files

first file

let file = document.getElementById('your_input_id').files[0]

show image onload

const reader = new FileReader()

let files = document.getElementById('your_input_id').files
reader.onload = async (event) => {
    document.getElementById('preview').setAttribute('src', event.target.result)
}
reader.readAsDataURL(files[0])
Samculo
  • 1
  • 1
-1

don't give this in file input value="123".

  $(document).ready(function(){  

      var img = $('#uploadPicture').val();

  });
lurker
  • 53,004
  • 8
  • 60
  • 93
Md Shahriar
  • 859
  • 6
  • 7