I am new to javascript and want to load the file without having to click on the load file button
I am using the following script and I want the text to be loaded aut
Respond to the document's ready
event:
$(document).ready( loadFileAsText );
If you don't want to use jQuery for simple compatibility with multiple browsers, then see this answer: pure JavaScript equivalent to jQuery's $.ready() how to call a function when the page/dom is ready for it
You can just call the function on it's own like this:
loadFileAsText();
Try adding the onchange
attribute, this will call functions when changes have been made to that input.
<input type="file" id="fileToLoad" onchange="loadFileAsText()">
Demo
function loadFileAsText(){
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent){
document.getElementById("inputTextToSave").value = fileLoadedEvent.target.result;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
<table><tr>
<td>Select a File to Load:</td>
<td><input type="file" id="fileToLoad" onchange="loadFileAsText()"></td>
<!-- ^^ onchange attribute added ^^ -->
</tr><tr>
<td colspan="2"><textarea id="inputTextToSave" style="width:512px;height:256px"></textarea></td>
</tr></table>
If you have any questions about the above source code please leave a comment below and I will get back to you as soon as possible.
I hope this helps. Happy coding!
You can do it using Javascript events. for ex: you can call like below:
<input type="file" id="fileToLoad" onblur="loadFileAsText()">