Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
JavaScript how can I get the data outside " myForm.addEventListener"?

I'm new here. I found a wonderful Skript on github. My questions: how can I get the data outside " myForm.addEventListener" I tried to declare it as global Variable, but in me case not work I hope Yu cann halp me.

    const myForm = document.getElementById("myForm");
    const csvFile = document.getElementById("csvFile");

    function csvToArray(str, delimiter = ",") {

      // slice from start of text to the first \n index
      // use split to create an array from string by delimiter
      const headers = str.slice(0, str.indexOf("\n")).split(delimiter);

      // slice from \n index + 1 to the end of the text
      // use split to create an array of each csv value row
      const rows = str.slice(str.indexOf("\n") + 1).split("\n");

      // Map the rows
      // split values from each row into an array
      // use headers.reduce to create an object
      // object properties derived from headers:values
      // the object passed as an element of the array
      const arr = rows.map(function (row) {
        const values = row.split(delimiter);
        const el = headers.reduce(function (object, header, index) {
          object[header] = values[index];
          return object;
        }, {});
        return el;
      });

      // return the array
      return arr;
    }

    myForm.addEventListener("submit", function (e) {
      e.preventDefault();
      const input = csvFile.files[0];
      const reader = new FileReader();

      reader.onload = function (e) {
        const text = e.target.result;
        const data = csvToArray(text);
        document.write(JSON.stringify(data));
      };
      
      reader.readAsText(input);
    });
<head> </head>
<body>
  <form id="myForm">
    <input type="file" id="csvFile" accept=".csv" />
    <br />
    <input type="submit" value="Submit" />
  </form>

</body>

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You can construct the FileReader and define its .onload method anywhere. You can also call its .readAsText method anywhere, but be aware that the code there makes the assumption that the "csvFile" element has an array-like .files property containing at least one file for it to read. (Also note that even though .onload appears earlier in the script than .readAsText, it doesn't get applied until afterward -- it's how the browser knows that .readAsText got a result.)

If that assumption is true as soon as the page loads, you can do everything right away (such as in a DOMContentLoaded listener). On the other hand, if the assumption only becomes valid after the user completes some form field(s), you can't read it much earlier than the submit event listener.

Any action you want to take with the text from the file should happen inside the reader's .onload method because that's where the contents of the file first become available to your script. The existing code makes a nice array of row objects (bound to data), then audaciously overwrites the whole webpage with it (after encoding it to a JSON string.)

You'd probably rather write a function that loops through each column (property) within each row (object) and does something with the value -- For starters, you could print each key/value pair to the browser console, like:

for (const thisRowObj of data){
  for (const thisKey in thisRowObj){
    const thisValue = thisRowObj[thisKey];
    console.log(`${thisKey}: ${thisValue}`);
  }
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda