0

I'm having a strange issue where 'document.write' will print up into the 'For' loop, but will not print after the 'For' loop. In the function test(), 1st and 2nd 'document.write' will print, but the 3rd one does not. Please help.

<script>
const myForm=document.getElementById("myAvgForm");
const csvFile=document.getElementById("csvFile");
myForm.addEventListener("submit", function (e) {
    e.preventDefault();
    const f = csvFile.files[0];
    const reader = new FileReader();

    reader.onload = function (e) {
        test(document.getElementById("symbol").value, e.target.result);
    };

    reader.readAsText(f);
});

function test(symbol, text)
{
    var lines = text.split("\n");
    symbol = symbol.toUpperCase();
    
    document.write("Begining of file<br>");                // 1.  prints
    
    for (var i=0; i<lines.length; i++) {
        var fields = lines[i].split(",");

        if (fields[2].includes(symbol)) {
            document.write(i + ". " + lines[i] + "<br>");  // 2.  prints
        }
    }

    document.write("End of file");                         // 3.  doesn't print
}

</script>
itchibahn
  • 79
  • 2
  • 8
  • 2
    [why is document.write bad](https://stackoverflow.com/questions/802854/why-is-document-write-considered-a-bad-practice) – Barmar Aug 25 '21 at 22:24
  • 2
    I have a hunch that your file ends with a newline, and on the last empty line the attempt to read `fields[2].includes` therefore crashes. If that is the case, you should see an error in the devtools console. – CherryDT Aug 25 '21 at 22:51
  • Thanks for a reply. I'm not using any devtools, just Notepad++ and straight sFTP to webhost. I've looked at the text file, and sure enough, there were a last line that was empty. I deleted that last empty line, but the result was still the same. – itchibahn Aug 25 '21 at 23:14
  • I think you are right about it. I commented out the that line containing "includes", and that last write does print.. I tried 'match' instead of 'includes' and still same issue. – itchibahn Aug 25 '21 at 23:28

1 Answers1

1

You need to tell the browser that writing has finished, by putting document.close() after the last write call.

Browsers may use a buffer to capture the writes, and calling close() will flush the buffer to the page.

Furthermore, to deal with empty lines, do a length check first in the if:

if (fields.length > 2 && fields[2].includes(symbol)) {
Peter B
  • 22,460
  • 5
  • 32
  • 69
  • Thanks for a reply. I tried as you suggested by adding document.close() at the end of the test() function, but didn't make any difference. – itchibahn Aug 25 '21 at 23:11
  • WORKS!!!! Wow, how strange. I deleted the last empty line in the text file, and it didn't work. But the simple check of length does the trick. Thank you very much!!! – itchibahn Aug 25 '21 at 23:52