[英]reading txt file into a textarea using javascript
Here is my html and javascript code using document.ready
function html script here... 这是我在这里使用
document.ready
函数html脚本的html和javascript代码...
<textarea id="recipients" name="recipients" class="form-control"></textarea>
<input name="file" type="file" id="files" class="form-control" value="">
<a id="fetch_number" class="btn btn-primary btn-sm" href="">pull text file</a>
Here is the javascript code: 这是JavaScript代码:
$(document).ready(function() {
$('#fetch_number').on('click', function() {
var files = document.getElementById('files').files;
if (!files.length) {
alert('Please select a file!');
return;
}
if (window.File && window.FileReader && window.FileList && window.Blob) {
var text_file = document.getElementById('files');
var files = text_file.files;
var file = files[0];
var extension = file.name.split('.').pop();
var start = 0;
var stop = file.size - 1;
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output = output.split("/\r\n|\n/");
var string = '';
for (var i=0; i < output.length; i++) {
var data = allTextLines[i].split(',');
string = data[1] + ',';
}
return string;
$("#recipients").text(string);
};
} else {
alert('The File APIs are not fully supported by your browser.');
}
});
});
Here is the javascript code I don't know what to do anymore if I do not browse for any text file it gives me response for the (!files.length)
, but I do not know why others don't work. 如果我没有浏览任何文本文件,这是JavaScript代码,我不知道该怎么办,它给了我对
(!files.length)
响应,但是我不知道为什么其他人不起作用。
You are having problems because 您遇到问题是因为
return string;
return string;
后调用代码return string;
return
from an asynchronous function return
Try something like this instead 尝试这样的事情
function readTextFile(file, callback, encoding) { var reader = new FileReader(); reader.addEventListener('load', function (e) { callback(this.result); }); if (encoding) reader.readAsText(file, encoding); else reader.readAsText(file); } function fileChosen(input, output) { if (input.files && input.files[0]) { readTextFile( input.files[0], function (str) { output.value = str; } ); } } $('#files').on('change', function () { fileChosen(this, document.getElementById('recipients')); });
<textarea id="recipients" name="recipients" class="form-control"></textarea> <input name="file" type="file" id="files" class="form-control" value=""> <script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.