Load a file automatically without using a click button

前端 未结 4 1795
走了就别回头了
走了就别回头了 2021-01-16 07:15

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

相关标签:
4条回答
  • 2021-01-16 07:45

    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

    0 讨论(0)
  • 2021-01-16 07:55

    You can just call the function on it's own like this:

    loadFileAsText();
    
    0 讨论(0)
  • 2021-01-16 08:00

    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!

    0 讨论(0)
  • 2021-01-16 08:04

    You can do it using Javascript events. for ex: you can call like below:

    <input type="file" id="fileToLoad" onblur="loadFileAsText()">
    
    0 讨论(0)
提交回复
热议问题