user2529462
user2529462

Reputation: 7

Read local file line by line using javascript

Am trying to achieve below task:

I tried something like below, but it's not working:

$.get('test.txt', function(myContentFile) {
    var lines = myContentFile.split("\r\n");
    var table = document.getElementById("myTableData");

    for(var i  in lines){
        var str = lines[i]
        var res = str.split(",");
        var row = table.insertRow(0);
        var cell1 = row.insertCell(0);
        var cell2 = row.insertCell(1);
        cell1.innerHTML = res[0];
        cell2.innerHTML = res[1];
    }

}, 'text');

Upvotes: 0

Views: 1724

Answers (2)

trincot
trincot

Reputation: 349964

Make sure you have included jQuery before your code executes, and have the table element with the correct id value in your document, something like this:

<table id="myTableData" border="1"><table>

Also make sure your text file (text.txt) resides in the same local folder as your html page.

If all these conditions are met, your code runs. Still, there are some things to tweek then. See the changes and comments I added to your code:

<html>
<head>
    <meta charset="UTF-8">
    <script src="http://code.jquery.com/jquery-1.9.0.js"></script>
</head>
<body>
<table id="myTableData" border=1><table>

<script type="text/javascript">
    $.get('test.txt', function(myContentFile) {
        console.log(myContentFile);
        // Added: strip ending new-lines from the retrieved text:
        myContentFile = myContentFile.replace(/[\r\n]$/, '');
        // Modified: split lines also when delimited by linefeeds only:
        var lines = myContentFile.split(/\r\n|\n/);
        var table = document.getElementById("myTableData");

        for(var i  in lines){
            var str = lines[i]
            var res = str.split(",");
            // Modified: remove argument to add rows to the end of the table
            var row = table.insertRow();
            var cell1 = row.insertCell(0);
            var cell2 = row.insertCell(1);
            cell1.innerHTML = res[0];
            // Modified: test that second element exists to prevent "undefined" output
            cell2.innerHTML = res[1] ? res[1] : '';
        }
    }, 'text');
</script>
</body>
</html>

I put the following test.txt file in the same folder:

This is a test, with something in second column
And a second line, that also has a second column
The third line just has one value

Then, when I open the html page in the browser, I get this output:

| This is a test                    | with something in second column |
| And a second line                 | that also has a second column   |
| The third line just has one value |                                 |

Upvotes: 1

Nvan
Nvan

Reputation: 1146

You have to put an <input type="file" id="myfile" /> before you can manipulate your file.

And then get your file with (jquery) :

var myFile = $('#myfile').prop('files');

Otherwise you can't access it.

Upvotes: 0

Related Questions