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 automatically in the text box.
<html>
<body>
<table>
<tr>
<td>Select a File to Load:</td>
<td>
<input type="file" id="fileToLoad">
</td>
<td>
<button onclick="loadFileAsText()">Load File</button>
<td>
</tr>
<tr>
<td colspan="3">
<textarea id="inputTextToSave" style="width:512px;height:256px"></textarea>
</td></tr>
</tr>
</table>
</body>
</html>
<script type='text/javascript'>
function loadFileAsText()
{
var fileToLoad = document.getElementById("fileToLoad").files[0];
var fileReader = new FileReader();
fileReader.onload = function(fileLoadedEvent)
{
var textFromFileLoaded = fileLoadedEvent.target.result;
document.getElementById("inputTextToSave").value = textFromFileLoaded;
};
fileReader.readAsText(fileToLoad, "UTF-8");
}
</script>
Thanks in advance for the help.
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!
您可以像这样单独调用函数:
loadFileAsText();
You can do it using Javascript events. for ex: you can call like below:
<input type="file" id="fileToLoad" onblur="loadFileAsText()">
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.