javascript 一旦我选择输入类型 =“文件”,就在文本框中获取文件名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/22349686/
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
Getting file name in text box as soon as i choose with input type="file"
提问by krishna
<input type="file" name="img1" id="img1">
<input type="text" name="file_name" id="file_name">
What i want is as soon i choose file in input type="file" i want to get the file name in text box (name="file_name") without any click or submit button. I could not figure out the code for it. Please provide my the code and idea.
我想要的是,一旦我在输入类型 =“文件”中选择文件,我想在文本框中获取文件名(名称 =“文件名”),而无需单击或提交按钮。我无法弄清楚它的代码。请提供我的代码和想法。
回答by SajithNair
<input type="file" name="img1" id="img1" onchange="document.getElementById('file_name').value = this.value">
<input type="text" name="file_name" id="file_name">
You can add .split('\\').pop()
to the end of this.value
, if you want to get rid of the c:\fakepath
你可以添加.split('\\').pop()
到 的末尾this.value
,如果你想去掉c:\fakepath
Without the c:\fakepath
没有 c:\fakepath
<input type="file" name="img1" id="img1" onchange="document.getElementById('file_name').value = this.value.split('\').pop().split('/').pop()">
<input type="text" name="file_name" id="file_name">
回答by krishna
you can use onchange in jquery like this
你可以像这样在 jquery 中使用 onchange
$("#img1").change(function(e){
$("#file_name").val($("#img1").val().split('\').pop().split('/').pop(););
});
add this line in <head>
of html
在<head>
html 中添加这一行
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
回答by Johan
The following will show only the filename in file_name textbox.
以下将仅显示 file_name 文本框中的文件名。
<input type="file" name="img1" id="img1" onchange="updateFileName()">
<input type="text" name="file_name" id="file_name">
<script>
function updateFileName() {
var img1 = document.getElementById('img1');
var file_name = document.getElementById('file_name');
var fileNameIndex = img1.value.lastIndexOf("\");
file_name.value = img1.value.substring(fileNameIndex + 1);
}
</script>
回答by Shijin TR
回答by Blackrabbit99
yourFileInputNode.on('change', function(e){
var file = e.target.files[0];
// you can get file name from file var and set it anewhere
})
回答by Raghu Veera
<input type="file" name="img1" id="img1" onchange="updateFileName()"><br><input type="hidden" name="file_name" id="file_name"><script>
function updateFileName() {
var img1 = document.getElementById('img1');
var file_name = document.getElementById('file_name');
var fileNameIndex = img1.value.lastIndexOf("\");
file_name.value = img1.value.substring(fileNameIndex + 1);
}
</script>