ed.
ed.

Reputation: 43

Jquery and Input File

How do you set the value of an input file using jquery?

$('input[type="file"]').val(value) just doesn't seem to work.

Any thoughts?

Upvotes: 2

Views: 597

Answers (5)

Firoj Mahmud
Firoj Mahmud

Reputation: 27

I have tried the similar things. But it's not feasible. But don't worry there is another way to do it. Here it is-

Suppose you have a input type in a div like -

 <div id="fileContainer1"><input type="file" size="52" id="reqFile1" name="reqFile1" onchange="javascript:anyMethod();"/></div>

First you have to remove the input type like below

var outer = divId; // Id of the div that contains the input type

outer.removeChild(outer.getElementsByTagName('input')[0]);

And again append it -

outer.appendChild(tempFile = document.createElement('input'));
tempFile.setAttribute('type', 'file', 0);

You can also add attribute of input type as follows

tempFile.setAttribute('id', 'reqFile1', 0);
tempFile.setAttribute('onchange',"javascript:anyMethod();", 0);
tempFile.setAttribute('size', 52);

Hope this will solve your problem what you are looking for.

Upvotes: 1

Robert Koritnik
Robert Koritnik

Reputation: 105029

Impossible because of security reasons

This is by no means possible, because it would pose a severe security threat. It's on users to decide whether they trust the site to upload sensitive files or not.

Example

Imagine dynamically setting file path (as you suggest) to some known file like some system file that holds user's preferences or something system security related.

This kind of security flaw would make browsers hackers heaven.

Upvotes: 0

stepanian
stepanian

Reputation: 11433

jquery uses javascript. You can't set/change the file path in a file input using javascript.

Upvotes: 3

Sampson
Sampson

Reputation: 268344

You cannot set the value of an input-file. It's read-only.

Upvotes: 0

Marek Karbarz
Marek Karbarz

Reputation: 29304

Your syntax is correct, however you can't set a value of a file input - this would be a huge security issue.

Upvotes: 1

Related Questions