OnionOfDoom
OnionOfDoom

Reputation: 27

HTML JavaScript print from file onto page

I have a problem with a little site (it's intended to work as a local site) I try to create. I want it to print text from local txt file onto the page. I want it to display it like this one,

<script type="text/javascript">
var arr = ['Heading 1','Para1','Heading 2','Para2','Heading 3','Para3'];
var result = arr.map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
document.getElementById('test').innerHTML = result ;
</script>

but I want it to do it from a file, like this one

<script>
 var fileInput = document.getElementById('inputfile');
 fileInput.addEventListener('change', function(e) {
     var file = fileInput.files[0];
     var reader = new FileReader();
     reader.onload = function(e) {
         document.getElementById('output').innerText = reader.result;
 };
     reader.readAsText(file);   
 });
 </script>

I tried to merge them together like this

   <script>
    var fileInput = document.getElementById('inputfile');
    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('output').innerHTML = reader.result.split("\n").map((val, i) => i%2===0 ? <h2>${val}</h2> : <p>${val}</p>).join('');
        };
    reader.readAsText(file[0]);   
 });
 </script>

But something is still not working right (after choosing the file to read, it does nothing) and I am not sure what am I doing wrong. I am green in javascript, so I would appreciate any help in that matter.

Upvotes: 0

Views: 381

Answers (1)

Joel Peltonen
Joel Peltonen

Reputation: 13402

Actually, now that I read that again - the only issue with your example is you were using file[0] instead of file

    <input type="file" id="inputfile" />
    <p id="output"></p>
    <script>
    var fileInput = document.getElementById('inputfile');
    fileInput.addEventListener('change', function(e) {
        var file = fileInput.files[0];
        var reader = new FileReader();
        reader.onload = function(e) {
            document.getElementById('output').innerHTML = reader.result.split("\n").map((val, i) => i%2===0 ? `<h2>${val}</h2>` : `<p>${val}</p>`).join('');
        };
     reader.readAsText(file);   // HERE! 
    });
</script>

Upvotes: 1

Related Questions