0

I was trying to read data from a txt file that can be choosen from an input type file and get stored info in an html content passing them trough an array.

There already are a lot of articles about that but no one really seems to fit at my case but following – which actually came from How to read txt file and save it in array in javascript in html which works fine but should be a bit “standardized” to be called from a function.

So what am trying now is something similar (becouse this is not really working) at that:

<!DOCTYPE html>
<html>
  <head>
    <meta content="text/html;charset=utf-8" http-equiv="Content-Type">
    <meta content="utf-8" http-equiv="encoding">
    <title>Read Text File</title> 
    <script>
      function splitARRAY(){
        var file = document.getElementById('myFile2');
        file.addEventListener('change', () => { var txtArr = [];
          var fr = new FileReader();
          fr.onload = function() {
            // By lines 
            var lines = this.result.split('\n');
            for (var line = 0; line < lines.length; line++) {
              txtArr = [...txtArr, ...(lines[line].split(" "))];
            }
            fr.onloadend = function() {
              console.log(txtArr);
              document.getElementById('other').textContent=txtArr.join("");
              document.getElementById("other2").innerHTML = txtArr[0];
              document.getElementById("other3").innerHTML = txtArr[1];
              document.getElementById("other4").innerHTML = txtArr[2];
              document.getElementById("other5").innerHTML = txtArr[3];
              
              console.log(txtArr[1]);
              
              fr.readAsText(file.files[0]);
            }
            )
          }
    </script>
  </head>
  <body> 
    <input type="file" id="myFile2" onchange="splitARRAY();">
    </br>
    <span id="other">txt variable 1</span> </br>
    <span id="other2">txt variable 2</span> <span id="other4">txt variable 4</span></br>
    <span id="other3">txt variable 3</span> <span id="other5">txt variable 5</span></br>
  </body> 
</html> 

Surely am doing something wrong becouse this way I do not obtain the variables data at all, but I do not really see what is wrong. By the way, should some one have a better solution am open to try it.

Endless
  • 34,080
  • 13
  • 108
  • 131
Dancode
  • 37
  • 7

1 Answers1

1
  • You have some syntax error in the end with )}
  • It's enogh to just use the fr.onload but this is never getting called cuz you call readAsText inside of it
  • you have also a problem with listening for change event. When it first change then you call the splitARRAY function that will only add a new eventlistener everytime it changes

Anyhow, here is a more modern approach using the new Read methods on blobs

var fileInput = document.getElementById('myFile2');
fileInput.addEventListener('change', async () => {
  var txtArr = []
  var file = fileInput.files[0]

  if (!file) return

  var text = await file.text()

  // By lines 
  var lines = text.split('\n')
  for (var line = 0; line < lines.length; line++) {
    txtArr = [...txtArr, ...(lines[line].split(" "))]
  }

  console.log(txtArr)
  document.getElementById('other').textContent = txtArr.join("")
  document.getElementById("other2").innerHTML = txtArr[0]
  document.getElementById("other3").innerHTML = txtArr[1]
  document.getElementById("other4").innerHTML = txtArr[2]
  document.getElementById("other5").innerHTML = txtArr[3]

  console.log(txtArr[1])
})
<input type="file" id="myFile2" >
</br>
<span id="other">txt variable 1</span> </br>
<span id="other2">txt variable 2</span> <span id="other4">txt variable 4</span></br>
<span id="other3">txt variable 3</span> <span id="other5">txt variable 5</span></br>

Other ways to add a EventListener other by the one provided above could be to do:

// opt: 2
var fileInput = document.getElementById('myFile2')
fileInput.onchange = async function (event) { ... }

// opt: 3
async function splitARRAY (event) { 
  // don't add any extra EventListener in here
  var txtArr = []
  var file = event.target.files[0]
  ...
}

<input type="file" onchange="splitARRAY">
Endless
  • 34,080
  • 13
  • 108
  • 131
  • ok, I can seei it is doing something in the code snippet tool provided inhere stackoverflow, it load the array and show one value. What I really miss is getting work in external file where is supposed to be used. You really mean that I do not have to call for a function in like ? – Dancode May 15 '21 at 07:36
  • 1
    Edited my answer... You can still use `onchange="splitARRAY(event);" ` if you like but then you have to do what i shown you in opt 3 – Endless May 15 '21 at 09:38
  • Oh, btw its safer to do innerText than innerHTML if it works for you – Endless May 15 '21 at 09:40
  • yes, innerText would be ok. I understand to have some kind of problems with eventlistener, actually I can't get that function work neither with option 2 - but it is not a news, always had problems with that. what it is really worrying myself is neither was able to make it work properly option 3, basically in the script area had called the function as you suggested pasting previous code from "var txtArr = []" but replacing with "var file = event.target.files[0]" where using fileInput.files[0] my browser neither gave me an error page. Thanks for your time but I didn't succeded – Dancode May 15 '21 at 10:57
  • I finally managed to correctly use eventlistener and I can confirm the solution you provided is ok. – Dancode May 15 '21 at 19:54