0

I am creating something whereby you can use a next and previous button to walk through different rows within a CSV. The first step of my process is to retrieve all of the rows within the CSV file. To do this I have created the following function.

function getRows() {
    var regex = /^([a-zA-Z0-9\s\S_\\.\-:])+(.csv|.txt)$/;
    if (regex.test($("#fileOne").val().toLowerCase())) {
        if (typeof (FileReader) != "undefined") {
            var reader = new FileReader();
            reader.onload = function (e) {
                return e.target.result.split("\n");
            };
            reader.readAsText($("#fileOne")[0].files[0]);
        } else {
            alert("This browser does not support HTML5.");
        }
    } else {
        alert("Please upload a valid CSV file.");
    }
}

When the preview button is pressed, I am currently doing the following

$("#preview-btn").bind("click", function () {
    var rows = getRows();
    console.log(rows);
});

At the moment it is printing undefined to the console. The idea is that I display the first row in the preview-btn event, and then use a counter to display different rows in the next and previous button events. At the moment though I am trying to figure out why the rows are not being returned to me but instead I get undefined.

Am I missing something when I return the rows?

Thanks

katie hudson
  • 2,765
  • 13
  • 50
  • 93
  • The problem is because `reader.onload` happens *after* the `getRows()` function has executed – Rory McCrossan Nov 02 '16 at 12:58
  • The whole idea I was going after was to move this into its own function. If I place it back into the preview-btn event then I do not have as good control for stepping through the rows – katie hudson Nov 02 '16 at 13:35
  • A better idea is to pass a callback function in to `getRows()`. You can then call that from within `onload` and pass it the `e.target.result.split('/n')` data – Rory McCrossan Nov 02 '16 at 13:36

0 Answers0