Why is FileReader.readAsText() returning null? - javascript

I am trying to read a file in the same directory of an HTML and JavaScript file however it seems to be returning null. Below I have added the code I have from each file.
HTML File:
<html>
<!-- Code to call the Google Maps API and link style.css sheet -->
<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>
JavaScript File:
function get_parameters() {
alert("hi"); // Just to let me know the function is getting called
var freader = new FileReader();
var text;
freader.onload = function(e) {
text = freader.result;
}
freader.readAsText('./test.txt', "ISO-8859-1");
text = freader.result; // To my knowledge, this should be taking the current line freader is on and storing it into text
var div = document.getElementById('bottom_pane_options');
div.innerHTML = div.innerHTML + text;
}
test.txt
Iron
Aluminum
Steel
//etc. for x number of times (depends on data I have parsed previously)
All I would like is for JavaScript to read test.txt and parse it into an array (text). The issue is, when I click the button 'Try It', the alert pops up (telling me the function is being called) and text contains null. I am running all files off my computer and all are in the exact same directory.

Related

How to load an XML file in JavaScript, get specific info from it, and then display it through alert()?

So, I want to make a program that will be able to get user data(a ton of bug names separated by commas), go through, get data for each one, then display all of that data in a table. I have been through rewriting this like 5 times and still nothing happens. Anyone know what is wrong with this code?
My html code:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1 align="center">Bugs</h1>
<p>In the area below, type in each of the insects you want information
about, seperate them with a comma.</p>
<textarea id="insects"></textarea>
<br>
<button type="button" id="go">Find out!</button>
<br>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
document.getElementById('go').onclick = function() {
var input = document.getElementById('insects').value;
var splitted = input.split(',');
for (i = 0; i<splitted.length; i++) {
var bug1 = splitted[i];
var part1 = // I need to assign it to bug1 without any whitespace
var finish = part1.toLowerCase();
find1(bug1);
}
}
function find1(bug) {
var xmlDocument = $.parseXML("externalfile:drive-77136639a78ffb21e72c7c4dfe7f7bb73604aeb3/root/Bugs/bugs.xml");
var pain = $(xmlDocument).find("value[type='" + bug + "'] pain").text();
alert(pain); <!-- This is to see if it works -->
}
</script>
</body>
Here is my XML code(btw the XML file is called bugs.xml and yes they are in the same exact folder in My Drive/Bugs:
<?xml version="1.0" encoding="UTF-8"?>
<bugs>
<bug type="blisterbeetle">
<name>Blister Beetle</name>
<pain>55</pain>
<conservation></conservation>
<habitat></habitat>
<rarity></rarity>
<class></class>
<order></order>
<family></family>
<species></species>
<dangerous></dangerous>
<external></external>
</bug>
</bugs>

Trying to use array.push(); with newlines but in plain text, not html <br> tags

recently I have been trying to grab HTML form input data, add a prefix, then write that back into a <div> For example:
HTML:
<h1>Please enter Details</h1><hr>
GUID (Generator):<div id="guidInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input onkeyup="gen()" id="guidText" style="height: 16px;"></input>
</div>
ID:<div id="idInput" style="display:inline;">
<!-- Changed to an onkeyup="" method. Works the same but with less code. -->
<input type="number" type="number" onkeyup="gen()" id="idText" style="height: 16px;"></input>
</div>
<div id="command" class="command"></div>
JS:
$(document).ready(function(){
var command = ""; /*Here for future developement*/
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
});
function gen() {
var id = $('#idText').val();
var guid = $('#guidText').val();
var command = ""; /*Here for future developement*/
var tags = [];
tags.push("GUID "+guid);
tags.push("ID "+id);
command += tags.join("<br>");
command += ""; /*Here for future developement*/
document.getElementById('command').innerHTML = command;
}
This does what I want it to: https://imgur.com/a/QrwD7 But I want the user to download the output as a file. To do this I implemented FileSaver.js, and added this code to my files:
HTML (placed above the <div id="command" class="command"></div>):
<button onclick="saver()">Save</button>
JS:
function saver() {
var text = document.getElementById("command").innerHTML;
var newText = text.replace(/(<([^>]+)>)/ig,"");
var filename = ("File")
var blob = new Blob([text], {type: "text/plain;charset=utf-8"});
saveAs(blob, filename+".txt");
}
That grabs the content of the <div> containing the output, and triggers a download of File.txt. The contents of this file look like this (from imgur.com link above.):
GUID qwertyuiop<br>ID 12345
This is where I'm having my problem. I NEED the file to look like this:
GUID qwertyuiop
ID 12345
With a line break after every part. the <br> is for displaying it on the site, but I need some way to make sure it's on a separate line in the downloaded file, and having no HTML tags in the file.
var newText = text.replace(`<br>`, `\n`).replace(/(<([^>]+)>)/ig,"");
or
function gen(delimiter) {
// ... //
command += tags.join(delimiter);
return command;
}
function saver() {
// ... //
var newText = gen(`\n`);
// ... //
}
Your code is violating SRP: Single Responsibility Principle.
You are trying to do two things at the same time.
Prefixing and formatting in HTML are two different concerns and they should be separated.
After that, the answer will become obvious.

how to get textarea input from another HTML page

In a.html:
I have a textarea that is converted into a link after the user clicks the submit button. When the user clicks on the link they are redirected to b.html.
<textarea id="sentenceId">
</textarea>
<br>
<button type="button" id="buttonId" onclick="createLink(document.getElementById('sentenceId').value)">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"></a>
</p>
In b.html:
I would like to display the original text.
In script.js:
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
}
If you want to open a new page and get the text there, you could use a post-form and an input[type="hidden"] to send the text and display it afterwards.
If you wand the link to be sendable, you'd either have to encode the text as get-parameter or save it to a database and add the id of the entry to the link.
As #Kramb already mentioned, localStorage is a possibility, but only if you stay on the same browser and both pages have the same domain.
Using localStorage
The localStorage property allows you to access a local Storage object. localStorage is similar to sessionStorage. The only difference is that, while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the browsing session ends—that is, when the browser is closed.
a.html
function createLink(val) {
document.getElementById("link").innerHTML = val;
document.getElementById('buttonId').style.display = 'none';
document.getElementById('sentenceId').style.display = 'none';
localStorage.setItem("textArea", val);
}
b.html
function getText(){
var textVal = localStorage.getItem("textArea");
}
Another option would be to use a query string.
a.html
function navigateTo(val){
window.href.location = "b.html?text=" + val;
}
This will pass the value of the text from textarea with the url during navigation. Once b.html has loaded, you can do the following.
b.html
function getText(){
var url = window.location.href;
var queryIndex = url.indexOf("=") + 1;
var passedText = url.substring(queryIndex);
document.getElementById('foo').value = passedText;
}
This is possible using JavaScript. You can do an AJAX call to another page on you website, and search for an element to get its content. In you're case an textarea
I wrote an example on codepen.io for you. Click here
To make things simpler im using jQuery in this example.
So how does it work?
First of, include jQuery inside the <head> tag of you're website.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
I created the following structure
structure
root
scripts
jQuery.min.js
index.js
index.html
textarea.html
Contents of index.html
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Meta -->
<meta charset="UTF-8" />
<title>My New Pen!</title>
<script type="text/javascript" src="scripts/jquery.min.js"></script>
<!-- Styles -->
<link rel="stylesheet" href="styles/index.processed.css">
</head>
<body>
<button id="clickme">To load the textarea content, click me!</button>
<div id="content">The data from the textarea will be shown here, afte you click on the button :)</div>
<!-- Scripts -->
<script src="scripts/index.js"></script>
</body>
</html>
Contents of texarea.html
<textarea id="textarea">
I am the content of the textarea inside the textarea.html file.
</textarea>
Contents of index.js
(function() {
$(document).ready(function() {
/**
* The button which triggers the ajax call
*/
var button = $("#clickme");
/**
* Register the click event
*/
button.click(function() {
$.ajax({
url: "textarea.html",
type: "GET"
}).done(function(response) {
var text = $(response).filter("#textarea").html();
$("#content").append("<br/><br/><strong>" + text + "</strong>");
});
});
});
})()
So what does index.js do exactly?
As you can see i created an Ajax call to the textarea.html file. The .done function holds the response data. The data inside it can be anything depending on the content of the textarea.html file.
$(response).filter("#textarea").html();
The above piece of code filters out the #textarea div and then gets the innerHTML using the jQuery html() function.
If you want to get the value of the textarea through the [value] attribute, you can replace above line to
$(response).filter("#textarea").val();
I believe you want to do this:
function createLink() {
var textvalue = document.getElementById('sentenceId').value;
document.getElementById("link").innerHTML = textvalue;
document.getElementById("buttonId").className ="hideme";
document.getElementById("sentenceId").className ="hideme";
}
.hideme{
display: none;
}
<textarea id="sentenceId">
</textarea>
<br>
<button id="buttonId" onclick="createLink()">Submit
</button>
<p id="demo">
<a id ="link" href="b.html"/>
</p>

document.getElementById doesn't get newly entered HTML text input value

I use the following code.
The idea is to print the contents of the div with name "PrintThis" which incorporates the text input area "textarea1".
The problem is that getElementById only ever returns the string loaded with the page; "cake" in this case.
If I change "cake" to "pie" by clicking and typing into "textarea1" on the page then printContents still has "cake" not "pie".
<html>
<head> </head>
<script type="text/javascript">
function printFunction(divName) {
var printContents = document.getElementById(divName).innerHTML;
//Now call a script to print (not included)
}
</script>
<body>
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10" style="width:95%!important;" ">cake</textarea>
</div>
<input type="button" value="Print Div" onClick="printFunction('printThis')">
</body></html>
In my production version I also use AJAX to post the text area value back to the server, so could in theory use a page refresh, though that doesn't run, I tried using these options.
document.location.reload(true);
window.top.location=window.top.location;
The production version does have jQuery available too.
first of all you are trying to get innerHTML of the div, instead of the actual textarea.
secondly instead of trying to get innerHTML try using value.
http://jsfiddle.net/qdymvjz8/
<div id="printThis" name="printThis">
<textarea id="textarea1" cols="1" rows="10">cake</textarea>
</div>
<input type="button" value="PrintDiv" onClick="printFunction('textarea1')">
function printFunction(divName) {
var printContents = document.getElementById(divName).value;
}
If you are having multiple items in your div in production then you can iterate through the children of the div and drag out the values.
function printFunction(divName) {
var printContents = document.getElementById(divName),
childItemCount = 0,
stringToPrint = '';
for (childItemCount; childItemCount < printContents.children.length; childItemCount++) {
stringToPrint += printContents.children[childItemCount].value;
}
console.log(stringToPrint);
//Now call a script to print (not included)
}

Element within iframe's div not accessible in the current code

I have 2 HTML files namely a.html and b.html, One js file namely do.js.
Here are each the contents of each file:
a.html:
<head>
<script src="do.js" type="text/javascript"></script>
</head>
<body>
<button onClick = "doWork();">click me</button>
<iframe src = "b.html" id = "previewFrame"></iframe>
</body>
b.html (relevant part):
<div id = "container"></div>
do.js:
function doWork(){
var div = $('#previewFrame').contents().find('#container');
div.html("<input type = 'text' id = 'testElem' value = '12'><script>alert(document.getElementById('testElem').value);</script>");
}
When I run the above code, the content of the iframe gets replaced by the text box, however the alert fails.
I get a "type error" stating that document.getElementById... is null.
Can anyone please tell me what am I missing in the above code?
You are calling the Javascript function using document, but this object is from the parent document, not the document of the iframe, try with:
function doWork(){
var a = $('#previewFrame').contents().find('body');
a.html("<input type = 'text' id = 'testElem' value = '12'><sc"+"ript>alert($('#previewFrame').contents()[0].getElementById('testElem').value);</scr"+"ipt>");
}
See demo here.

Categories

Resources