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 badges3 Answers
Reset to default 6Usually 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.