Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!