getElementById returning null value - javascript

I'm tying to read and output a text file. The Chrome console complains:
caught TypeError: Cannot read property '0' of undefined FinanceDashBoard.html:22"
Not sure what I am doing wrong ?
The code is as follows:
<html>
<head>
<title>Read File (via User Input selection)</title>
</head>
<body>
<main>
<label>Load a text database file: <input type="file" id="txtfile" ></label>
</main>
<script type="text/javascript">
var dbFileElm = document.getElementById('txtfile');
dbFileElm.onchange = function() {
var filePath = dbFileElm.files[0];
var reader = new FileReader();
var output = ""; //placeholder for text output
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
}
reader.readAsText(filePath.files[0]);
}
// Ignore code below it doesn't work yet.
function displayContents(txt) {
var el = document.getElementById('main');
el.innerHTML = txt; //display output in DOM
}
</script>
</body>
</html>

Two mistakes.
1) Change this line:
reader.readAsText(filePath.files[0]);
to this:
reader.readAsText(filePath);
Because filePath is already: dbFileElm.files[0];
2) The main tag has no ID, so getting element by ID main will not work.
Just edit it to:
<main id="main">

You have no elements that have id="main"
Try something like...
<main id="main"> ...
Or if you're trying to populate your text box...
var el = document.getElementById('txtfile');

this post has answer to question
HTML input file selection event not firing upon selecting the same file
and if you set your input value to null, is working for me
dbFileElm.onChange = function() {
this.value = null;
var filePath = dbFileElm.files[0];
var reader = new FileReader();
var output = ""; //placeholder for text output
reader.onload = function (e) {
output = e.target.result;
displayContents(output);
}
reader.readAsText(filePath.files[0]);
}

Related

How can I load text file in javascript using fileReader? [duplicate]

This question already has answers here:
Javascript read file without using input
(3 answers)
Closed 9 months ago.
I'm trying to load simple text file in javascript, unfortunately with no success.
my code is:
var my_text:any;
var my_file:File = new File([], "C:\\Users\\riki7\\Downloads\\classes.txt");
var reader = new FileReader();
reader.onload = function() {
my_text = reader.result;
};
reader.readAsText(my_file);
alert(my_text);
after this code runs, I would expect to see classes.txt file content in pop-up alert, instead I get 'undefined'.
my file contains a, b, c.
does anyone know what is my problem? maybe the first parameter for File() constructor?
You have to use html tag <input type="file" id="input" /> and then hung a event listener on it, like that
const inputElement = document.getElementById("input");
inputElement.addEventListener("change", handleFiles, false);
function handleFiles() {
const fileList = this.files; /* now you can work with the file list */
}
then after simply bypass your file into the FileReader
const reader = new FileReader();
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
reader.readAsDataURL(file);
And i guess that would be it.
You can find more examples there: https://developer.mozilla.org/en-US/docs/Web/API/File_API/Using_files_from_web_applications
Having your code where your alert runs upfront the callback function. If you need to see alter with the content, simply move your alert into the callback function:
reader.onload = function() {
my_text = reader.result;
alert(my_text);
};
because my_text is not ready when you call alert outside.
<input type="file" id="selectedFile">
<p id="display"></p>
<script>
var fr = new FileReader();
let test;
document.getElementById('selectedFile').addEventListener('change', x);
function x() {
fr.onload = ()=>{
document.getElementById('display').innerText = fr.result;
test = fr.result;
alert(fr.result);
}
fr.readAsText(this.files[0]);
}
</script>
<html>
<head>
<script>
var fileReadEvent = function(event) {
var input = event.target;
var reader = new FileReader();
reader.onload = function(){
var text = reader.result;
alert(text)
};
};
</script>
</head>
<body>
<input type='file' accept='text/plain' onchange='fileReadEvent(event)'><br>
</body>
</html>

JavaScript - Reading file with HTML5 FileReader

I'm currently learning JavaScript and I'm struggling to read a txt file and use its contents in the program, what I have so far:
fileBtn.addEventListener("change", function()
{
var content = [];
var file = fileBtn.files[0];
readFile(file, function(data)
{
console.log(JSON.parse(data));
//content.push(JSON.parse(data)) doesn't work, data is undef.
});
});
and a function readFile
function readFile(file, f)
{
var reader = new FileReader();
reader.onload = function(evt)
{
f(evt.target.result);
};
reader.readAsText(file);
}
My txt file is currenty only containing a "1", and it logs this number to the console but I can't work with it, if I try to push it into an array the values is suddenly undefined. My goal is to use the content of the file in the program later on
1 . no need to use JSON.parse if the text file only contain string .
data is containing all the text file content
2 . you need to put var content = [];
globally and not inside the function readFile
follow this snippet of code i think it will solve your problem
<html lang="en">
<head>
<meta charset="utf-8">
</head>
<body>
<label for="file-upload" class="custom-file-upload">
Custom Upload
</label>
<input id="file-upload" type="file" />
<input id="log-content" type="button" value="Click Me"/>
</body>
<script>
var content = [];
function readFile(file, f) {
var reader = new FileReader();
reader.onload = function (evt) {
f(evt.target.result);
};
var text = reader.readAsText(file);
}
var fileBtn = document.getElementById("file-upload");
var logContnt = document.getElementById("log-content");
logContnt.addEventListener("click", function () {
alert(content);
})
fileBtn.addEventListener("change", function () {
var file = fileBtn.files[0];
readFile(file, function (data) {
content.push(data);
});
});
</script>
</html>

array data is showing in console but when i printing in html it is not showing empty array in angularjs

I am getting data from a file then that data is pushing to array.array data can view in console but that data is not displaying in html page.
If i use any button then i able to see that data in html page.
var app = angular.module('xlsxApp', []);
app.controller('xlsxCtrl', ['$scope', function($scope) {
$scope.finaldata = [];
$scope.UploadFiles = function(files) {
var f = files[0];
var reader = new FileReader();
reader.readAsBinaryString(f);
reader.onload = function(e) {
var data = e.target.result;
/*Converts the excel data in to object*/
var workbook = XLSX.read(data, {
type: 'binary'
});
/*Gets all the sheetnames of excel in to a variable*/
var sheet_name_list = workbook.SheetNames;
/*This is used for restricting the script to consider only first sheet of excel*/
sheet_name_list.forEach(function(y) { /*Iterate through all sheets*/
/*Convert the cell value to Json*/
var exceljson = XLSX.utils.sheet_to_json(workbook.Sheets[y]);
$scope.finaldata = exceljson;
console.log("finaldata :: ", $scope.finaldata);
});
}
}
$scope.test = function() {
console.log("finaldata :: ", $scope.finaldata);
}
}]);
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.7.7/xlsx.core.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xls/0.7.4-a/xls.core.min.js"></script>
</head>
<body ng-app="xlsxApp" ng-controller="xlsxCtrl">
<div class="container">
<div class="form-inline">
<input type="file" class="form-control" name="file" id="excelfile" accept="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, application/vnd.ms-excel" onchange="angular.element(this).scope().UploadFiles(this.files)" />
</div>
<button ng-click="test()">preview</button>
{{finaldata[0]}}
</div>
</body>
you get the object in console not an array.so,in html you bind {{finaldata}}/if you want value {{finaldata['C']}}
reader.onload() is evaluated outside the AngularJS environment. You should can $timeout service to update the UI view in next digest cycle
$timeout(function(){
$scope.finaldata = exceljson;
}, 0)
Use $scope.apply() to evaluate changes coming from outside angular.js
The reason why you see result when press a button - you probably have ng-click on the button that implicitly runs through $scope.apply() and applies your changes already sitting in the scope.

Creating an option menu based on a text file?

I am trying to automatically create an option menu (using HTML and JavaScript) based on the contents of a text file. What I would like is for each option in the menu to be a line in the text document.
Here is the JavaScript:
function get_parameters() {
alert("get_parameters() called"); // these alerts are just to tell me if that section of the code runs
var freader = new FileReader();
var text = "start";
freader.onload = function(e) {
text = freader.result;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
With this code, all I'm trying to accomplish is reading the file and printing to the div "bottom_pane_options" but I can't find any reason why it doesn't work. If my way isn't the most efficient, could you please give me code that would work?
Thanks.
--EDIT--
Here is the HTML
<!DOCTYPE html>
<html>
<head>
<title>Culminating</title>
<link href="style.css" rel="stylesheet" type="text/css">
<script
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyCJnj2nWoM86eU8Bq2G4lSNz3udIkZT4YY&sensor=false">
</script>
<script>
// Calling the Google Maps API
</script>
</head>
<body>
<div class="content">
<div id="googleMap"></div>
<div id="right_pane_results">hi</div>
<div id="bottom_pane_options">
<button onclick="get_parameters()">Try It</button>
</div>
</div>
</body>
<script type="text/javascript" src="./javascript.js"></script>
</html>
You need to set the <div> text in the callback instead of right after you start loading:
freader.onload = function(e) {
text = freader.result;
/*************
** TO HERE **
************/
alert('file has been read');
}
/* MOVE THIS */
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
/*************/
Because the file was not read yet when you are runing div.innerHTML = div.innerHTML + text;.
That's why there are callbacks.
See https://developer.mozilla.org/en-US/docs/Web/API/FileReader :
The FileReader object lets web applications asynchronously read the
contents of files [...]
Use this instead :
freader.onload = function(e) {
text = freader.result;
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
alert('file has been read');
}
freader.onerror = function(e) {
alert('freader encountered an error')
}
freader.readAsText('./test.txt', "ISO-8859-1");

To display text from a txt file using javascript

How to read text from a txt file with one button to browse the file and other button to display text. Pls help me in getting the code. i have tried many codes but othing worked. some code was like this. Thanks in advance
<!DOCTYPE html>
<html>
<head>
<title>reading file</title>
<script type="text/javascript">
var reader = new FileReader();
function readText(that){
if(that.files && that.files[0]){
var reader = new FileReader();
reader.onload = function (e) {
var output=e.target.result;
//process text to show only lines with "#":
output=output.split("\n").filter(/./.test, /\#/).join("\n");
document.getElementById('main').innerHTML= output;
};//end onload()
reader.readAsText(that.files[0]);
}//end if html5 filelist support
}
</script>
</head>
<body>
<input type="file" onchange='readText(this)' />
<div id="main"></div>
</body>
</html>
You should properly read an article like this: http://www.html5rocks.com/en/tutorials/file/dndfiles/
Dont think this line is working properly:
output=output.split("\n").filter(/./.test, /\#/).join("\n");
Try changing it to:
output=output.split("\n").filter(function(l) {
//return /^\#/.test(l); // Starting with #
return l.indexOf('#') > -1; // Containing #
}).join("\n");
It would be interesting to see if this would work as well:
output=output.split("\n").filter(/\#/.test.bind(/\#/)).join("\n");
The second arguments passed to the .filter method is the context:
array.filter(callback[, thisObject])
Get the input file, use FileReader() to read it,on file load get text that matches the pattern. Finally display it through "main" div. Should work..
HTML :
<input id="fileInput" type="file"/>
<div id="main"></div>
jQuery :
$(function(){
$("#fileInput").change(function(e){
var myFile = e.target.files[0];
var reader = new FileReader();
reader.onload = function(e){
var output = e.target.result;
output=output.split("\n").filter(/./.test, /\#/).join("\n");
$("#main").text(output);
};
reader.readAsText(myFile)
});
}
)
Demo

Categories