jQuery 在文本输入中写入

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6382908/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 20:45:34  来源:igfitidea点击:

jQuery write in a text input

jquery

提问by DiegoP.

I have a form upload

我有一个表格上传

I need a jQuery function that will write in a hidden text input what is written in the input file.

我需要一个 jQuery 函数,它将在隐藏文本输入中写入输入文件中写入的内容。

So I have :

所以我有 :

<input class="addFile" id="field2" name="fileLyric" type="file" />

Whatever will be written there by the uploading (obviously the file path) should be then automatically written in a hidden text input

上传时将写入的任何内容(显然是文件路径)都应该自动写入隐藏文本输入中

<input id="field2hidden" name="fileLyrichidden" type="text" style="display:none"/>

Is there a way to achieve this?

有没有办法实现这一目标?

Thank you!

谢谢!

回答by DanielB

This will do it, but as the others already said, this will not be the full path for security reasons.

这将做到这一点,但正如其他人已经说过的那样,出于安全原因,这不是完整的路径。

Add a change listener, so the value will be updated if the user has selected a file.

添加更改侦听器,以便在用户选择文件时更新该值。

$('#field2').change( function() {
    $('#field2hidden').val($(this).val());
});

Here is a jsFiddlefor demonstration. Try it in different browsers and you'll see what you get as path.

这是一个用于演示的jsFiddle。在不同的浏览器中尝试,你会看到你得到的路径。

回答by JohnP

You can't take the actual path of the file from the input box. Most browsers will put a fake path so that you can't use it. This is a security feature of the browser.

您无法从输入框中获取文件的实际路径。大多数浏览器会放置一个假路径,以便您无法使用它。这是浏览器的安全功能。

回答by GordonM

$('#field2hidden').val ($('#field2').val ())

Wouldn't that do it?

这样做不行吗?

EDIT: It would get the filename but the path section is deliberately obscured. You can't (or at least shouldn't) be able to get the full path in javascript as it could expose information about the user's filesystem.

编辑:它会得到文件名,但路径部分被故意掩盖。您不能(或至少不应该)能够在 javascript 中获取完整路径,因为它可能会暴露有关用户文件系统的信息。

回答by alex

You can not reliable get the path used to upload a file (Chrome will say the path is C:\fakepath\.... Best you can do is get the filename.

您无法可靠地获取用于上传文件的路径(Chrome 会说路径是C:\fakepath\...。最好的方法是获取文件名。