-4

This is a follow up to this question: https://stackoverflow.com/questions/14446447/how-to-read-a-local-text-file-in-the-browser

This provided solution code works, but I need to output the result to an Element instead of the Console.

<input type="file" onchange="this.files[0].text().then(t => console.log(t))">

I've tried replacing t => console.log(t) with document.getElementById("output").innerText = t but that results in a Syntax Error.

What is the simplest and shortest way to implement this? Thank you.

I don't really understand arrow functions, but I looked into them and tried a variety of combinations that might work. I assume this has something to do with their syntax.

name
  • 1
  • Here, the use of the arrow function `t => console.log(t)` is more or less the same thing as 1) defining a function: `function myFunction(t) { console.log(t); }`, and then 2) passing this function as the`then` callback: `this.files[0].text().then(myFunction)` . – Pac0 Feb 21 '23 at 18:28
  • 4
    Are you setting `onchange="this.files[0].text().then(t => { document.getElementById('output').innerText = t })"` ? The nested-double-quotes won't have been helping, try single quotes. – motto Feb 21 '23 at 18:30
  • Thanks @motto, this was the issue. Both the missing brackets, which I did not understand, and the nested-double-quotes, which I just didn't think about, for lack of experience. – name Feb 21 '23 at 18:42

1 Answers1

0

This isn't necessarily a arrow function question. There's a lot going on in that little onchange handler.

<input type="file" onchange="this.files[0].text().then(t => document.getElementById('output').innerText = t)">

this is the file input

.files[0] returns the first file selected

.text() returns a promise that resolves when the text is read from the file

.then( waits for the promise to finish and then calls the arrow function that follows

t=> document.getElementById('output').innerText = t is the arrow function. The first paramater t will have the text value, so we use that to assign the innerText of your destination element.

Finally, note that I surrounded the id output in single quotes, so the HTML parser doesn't think it's the matching close quote " for the onchange attribute.

NetByMatt
  • 703
  • 4
  • 13