最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Get value of file upload to a hidden text box - Stack Overflow

programmeradmin0浏览0评论

I'm trying to get the value or file path from a html file upload control to a hidden input text box as soon as I select a file.

<input type="file" name="some_name" id="file" />
<input type="text" name="text_name" id="abc" style="display:none;" value=""/>

and my script looks like:

$('#file').live('change', function(){ alert("yes"); });

so I get the alert box but I would like to change the value of the hidden input field to the path of the file I select. Any help to solve this problem is highly appreciated.

I'm trying to get the value or file path from a html file upload control to a hidden input text box as soon as I select a file.

<input type="file" name="some_name" id="file" />
<input type="text" name="text_name" id="abc" style="display:none;" value=""/>

and my script looks like:

$('#file').live('change', function(){ alert("yes"); });

so I get the alert box but I would like to change the value of the hidden input field to the path of the file I select. Any help to solve this problem is highly appreciated.

Share Improve this question asked Dec 11, 2012 at 21:58 VinitVinit 1,82517 silver badges38 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 6

Usually you get an element's value with $('#elementId').val(), but in the case of a an <input type="file"> you can't, because of security restrictions. There is no way to know the local file path (at least none that works consistently on all browsers).

To get the file path of an upload control <input type='file'> you can do the following:

var value = $('#elementID').val();
var value = value.substr(value.lastIndexOf('\\') + 1);

This will trim off any file path that es before the filename. In the case of IE and Firefox the full file path and in the case of Chrome and Safari the C:\Fake Path.

See the associated jsfiddle:

Fiddle

Does it work ?

$('#file').change(function() {
  $('#abc').val($(this).val());
});

I guess it doesn't: see bfavaretto answer.

发布评论

评论列表(0)

  1. 暂无评论