插入值到输入/JavaScript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17631305/
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-10-27 09:01:13 来源:igfitidea点击:
Insert value to input / JavaScript
提问by Nave Tseva
I have the following JS / HTML code:
我有以下 JS/HTML 代码:
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="name();">
</div>
<script>
function name() {
var fileName = document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').innerHTML = 'Fred Flinstone';
}
</script>
I want that after I upload file, the file-name will shown in the tput text, but this cide doesn't work.
我希望在上传文件后,文件名将显示在 tput 文本中,但此 cide 不起作用。
How can I fix it?
我该如何解决?
Update : The file name should be inside the input text
更新:文件名应该在输入文本内
回答by Hieu Le
回答by amatellanes
You can try this code:
你可以试试这个代码:
<!DOCTYPE html>
<html>
<head>
<script>
function myFunction()
{
var fileName =document.getElementById("file_upload").value;
var fnSplit = fileName.split(/[\/\]/);
fileName = fnSplit[fnSplit.length - 1];
document.getElementById('file_info').value = fileName
}
</script>
</head>
<body>
<input type="text" class="file" name="file_info" id="file_info">
<div class="file_upload">
<input type="file" id="file_upload" onchange="myFunction();">
</div>
</body>
</html>
回答by Jonathan
Do it like this:
像这样做:
HTML
HTML
<div class="file_upload">
<input type="file" id="file_upload">
</div>
<div id="file_info"></div>
JS
JS
function name(file) {
var reader = new FileReader();
reader.readAsText(file);
reader.onload = function (event) {
document.getElementById('file_info').innerHTML = "Filename: " + file.name + "\nContent: " + event.target.result;
};
reader.onerror = function () {
alert('Unable to read ' + file.name);
};
}
document.getElementById('file_upload').onchange = function () {
name(this.files[0]);
};