So I have this program where I update a .txt file and it shows me the content of it. But now I want it to show me only when I click on the button. But it´s not woking.
<div id="output"></div>
<button id="btn">Click me</button>
<script type="text/javascript">
document.getElementById("btn").addEventListener("click", function () {
const input = document.getElementById("inputfile");
if (!input.files.length) {
alert("No file selected!");
return;
}
const fr = new FileReader();
fr.onload = function () {
if (!fr.result) {
return;
}
const resultAsArray = fr.result.split('\r\n');
let index = 0;
const displayInterval = setInterval(() => {
if (index === (resultAsArray.length - 1)) {
clearInterval(displayInterval);
return;
}
let html$ = document.getElementById('output').innerHTML;
html$ += '<div>' + resultAsArray[index] + '</div>';
document.getElementById('output').innerHTML = html$;
index++;
}, 1000);
}
fr.readAsText(this.files[0]);
});
</script>
I got this javascript code from the Internet
Try doing this:
Wherever you're doing the HTML Stuff:
<button id="button-id">Click Me</button>
Then, inside your JavaScript:
let button = document.getElementById('button-id')
button.addEventListener("click", theFunction);
function theFunction() {
//Code to be executed when the button is pressed..
}
Give an id to button then use this code.
document.getElementById('buttonID')
.addEventListener('click', function (){
//statements
})
You can name the function, then change to get files from input, so just replace this.files[0] to file than you get from input.
<input type="file" name="inputfile" id="inputfile">
<br>
<div id="output"></div>
<button onclick="test()">Click me</button>
<script type="text/javascript">
function test() {
var inputElement = document.getElementById('inputfile');
var fileList = inputElement.files;
var fr = new FileReader();
fr.onload = function () {
if (!fr.result) {
return;
}
const resultAsArray = fr.result.split('\r\n');
let index = 0;
const displayInterval = setInterval(() => {
if (index === (resultAsArray.length - 1)) {
clearInterval(displayInterval);
return;
}
let html$ = document.getElementById('output').innerHTML;
html$ += '<div>' + resultAsArray[index] + '</div>';
document.getElementById('output').innerHTML = html$;
index++;
}, 1000);
}
fr.readAsText(fileList[0]);
}
</script>