Here is my html and javascript code using document.ready
function html script here...
<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:
$(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.
You are having problems because
return string;
return
from an asynchronous function 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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.