Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load text from local .txt file into html textarea using JavaScript

I have a <textarea> element and a button that calls a loadFile() JavaScript function. I want this function to allow me to load the text from a .txt file on my local machine into the textarea. Any help with this would be greatly appreciated!

like image 517
Jed Avatar asked Nov 10 '15 21:11

Jed


1 Answers

You can use the File and FileReader objects to read local files.

You can use an input element with type="file" to allow the user to select a file.

<input id="myFile" type="file"/>
<textarea id="myTextArea" rows="4" columns="20"></textArea>

After the user has selected a file, you can get the File object from the input element. For example...

var file = document.getElementById("myFile").files[0];

You can then use a FileReader object to read the file into the text area. For example...

var reader = new FileReader();
reader.onload = function (e) {
    var textArea = document.getElementById("myTextArea");
    textArea.value = e.target.result;
};
reader.readAsText(file);
like image 54
Bobby Orndorff Avatar answered Oct 03 '22 04:10

Bobby Orndorff