0

Note:

The answers & comments below reflect the state of legacy browsers in 2009. Now you can actually set the value of the file input element dynamically/programatically using JavaScript in 2017.

See the answer in this question for details as well as a demo:
How to set file input value programatically (i.e.: when drag-dropping files)?

I want to set form fields using jquery, I make like this

$("#title").val('${media.title}'); 

for

<label>Media title</label>
<input type="text" name="title" id="title"/>

and it works properly,but when I make like this

 $("#fileName").val("${media.fileName}");

or

 $("#fileName").attr({value:'${media.fileName}'});

for

<label>upload file</label>
<input type="file" name="file" id="fileName"/>

it doesn't wok, can somebody help ?

Samuel Liew
  • 76,741
  • 107
  • 159
  • 260
palAlaa
  • 9,500
  • 33
  • 107
  • 166
  • 1
    Unrelated to the problem: why are you using jQuery to set the field values? Why not just ``? – BalusC May 18 '11 at 18:04
  • @BalusC, I learn jquery recently, and I want to use it :) – palAlaa May 18 '11 at 18:09
  • 1
    jQuery is fantastic, but please don't go overboard. Use the right tool for the job. You've those variables apparently already at your hands when you render the page from the server side on. You should then really use the server side language (EL in this case) to do the job instead of delegating the job to the webbrowser which might not have JavaScript enabled at all. Imagine that you've a button which says "Prefill those fields from the DB" then using jQuery (unobtrusively!) would be right. – BalusC May 18 '11 at 18:09
  • @BalusC, yes u r right, I'll return to using EL in setting form fields . – palAlaa May 18 '11 at 18:10
  • 1
    You're welcome. Note that you still cannot prefill the value of the `` field this way. HTML simply doesn't allow it. It's a huge security risk. See also this answer: http://stackoverflow.com/questions/1696877/how-to-set-a-value-to-a-file-input-in-html/1696884#1696884 – BalusC May 18 '11 at 18:13

2 Answers2

2

That ability is blocked by the browser itself because it is a security risk. The value property on an input element of type "file" is read-only.

Just think what a malicious user could do if they could automatically fill in the path, force a post, and collect a file on a server somewhere...

Cᴏʀʏ
  • 105,112
  • 20
  • 162
  • 194
1

file inputs are a special case of input element since it interacts with the user's file system. You can't specify a file; the user has to browse for it.

There's some more details about file input elements here.

josh3736
  • 139,160
  • 33
  • 216
  • 263