Javascript jQuery,选择输入文件并将其设置为另一个输入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29720794/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery, Select Input FILE and also set it to another INPUT
提问by Maxi
The website has 2 input fields, I only select 1 field and the other one is invisible. Now I want to change the .val() of the invisible one to the .val() of the selected one, so both fields upload the same file. How does that work?
该网站有2个输入字段,我只选择了1个字段,另一个是不可见的。现在我想将不可见的 .val() 更改为选定的 .val() ,因此两个字段都上传相同的文件。这是如何运作的?
If I do this:
如果我这样做:
$('#input_file').change(function() {
var fileSelect = $(this).val();
$('#hidden_input_file"]').val(fileSelect);
console.log(fileSelect);
});
I get this error: Uncaught InvalidStateError: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string.
我收到此错误:未捕获的 InvalidStateError:无法在 'HTMLInputElement' 上设置 'value' 属性:此输入元素接受文件名,该文件名只能以编程方式设置为空字符串。
回答by John Weisz
Your code is almost correct:
你的代码几乎是正确的:
$('#hidden_input_file').val(fileSelect);
This will make jQuery change the value of an input. However, the valueof input type="file"can never* be changed with JavaScript (nor Flash, nor any means programmatically). This is a security feature implemented in allend-user browsers to prevent websites from a trivial mischievery:
这将使 jQuery 更改输入的值。然而,值的input type="file"永远不能被*使用JavaScript(NOR闪存,NOR编程任何方式)改变。这是在所有最终用户浏览器中实施的安全功能,以防止网站发生微不足道的恶作剧:
$('#hidden_input_file').on('blur', function (e) {
$('#hidden_input_file').val('c:\passwords.txt'); // won't work
});
Enabling the programmatical change of a file URL that is to be uploaded from a user's computer would be a monstroussecurity issue.
启用要从用户计算机上载的文件 URL 的编程更改将是一个可怕的安全问题。
*only applies to JavaScript on the web
*仅适用于网络上的 JavaScript

