I am trying to preview the files in the same page using the < embed> tag after clicking on them.
I found this way of displaying the directories from the file-system, but after I click on a file, either it downloads directly(ppt, pdf...) or opens in new page(jpeg, png)
help!
This is a screenshot of the result:Screenshot of webpage after dropping a file direcory
this is the HTML code:
<!DOCTYPE html>
<html>
<head>
<script src="jquery-3.2.1.min.js"></script>
</head>
<body>
<p>Drag files and/or directories to the box below!</p>
<div id="dropzone">
<div id="boxtitle">
Drop Files Here
</div>
</div>
<h2>Directory tree:</h2>
<ul id="listing">
</ul>
</body>
</html>
this is the javascript code:
let dropzone = document.getElementById("dropzone");
let listing = document.getElementById("listing");
function scanFiles(item, container) {
let elem = document.createElement("li");
elem.innerHTML = item.name;
container.appendChild(elem);
if (item.isDirectory) {
let directoryReader = item.createReader();
let directoryContainer = document.createElement("ul");
container.appendChild(directoryContainer);
directoryReader.readEntries(function(entries) {
entries.forEach(function(entry) {
scanFiles(entry, directoryContainer);
});
});
}
}
dropzone.addEventListener("dragover", function(event) {
event.preventDefault();
}, false);
dropzone.addEventListener("drop", function(event) {
let items = event.dataTransfer.items;
event.preventDefault();
listing.innerHTML = "";
for (let i=0; i<items.length; i++) {
let item = items[i].webkitGetAsEntry();
if (item) {
scanFiles(item, listing);
}
}
}, false);
Related
i hope you guys fine, well..
I'm doing a To Do List, and there is a problem in my code, which I've been trying to solve for a few days, and no effective results was made..
If you guys test in the snippet with me, i am sure, that will be more
clear to understand.
When i click in some list element, my javascript should change or add the className, and add a class call 'selected'.
because, when i will click in the remove button, they will delete all elements with 'selected' classList in the list. (as you can see in the code)
But the className a not being add to the tag in the first click, just works if i click in the element one more time.
i simplified my code, just to show the real problem:
Link to jsfiddle : https://jsfiddle.net/myqrzcs2/
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
const completedLine = document.querySelector('ol');
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
i.addEventListener('click', function semNomeDois() {
listas.forEach((j) => j.classList.remove('selected'));
this.classList.add('selected');
});
});
}
}
completedLine.addEventListener('click', umClick);
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.lista:focus {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
But how can i make the class be add, just in the first click, not in the second?
I think you got off on the wrong foot in programming this.
Here is the way I use, may it inspire you.
const
textoTarefa = document.getElementById('texto-tarefa')
, criarTarefa = document.getElementById('criar-tarefa')
, removerSelec = document.getElementById('remover-selecionado')
, listaTarefas = document.getElementById('lista-tarefas')
;
var li_selected = null
;
textoTarefa.oninput = () =>
{
criarTarefa.disabled = (textoTarefa.value.trim().length ===0 )
}
criarTarefa.onclick = () =>
{
listaTarefas.appendChild( document.createElement('li')).textContent = textoTarefa.value.trim()
textoTarefa.value = ''
textoTarefa.focus()
criarTarefa.disabled = true
}
listaTarefas.onclick = ({target}) =>
{
if (!target.matches('li')) return
if (!!li_selected && li_selected !== target ) li_selected.classList.remove('listaSelect')
li_selected = target.classList.toggle('listaSelect') ? target : null
removerSelec.disabled = !li_selected
}
removerSelec.onclick = () =>
{
listaTarefas.removeChild(li_selected)
li_selected = null
removerSelec.disabled = true
}
.listaSelect {
background: #ff0000c4;
}
ol#lista-tarefas {
cursor : pointer
}
<input id='texto-tarefa' type="text" value="">
<button id='criar-tarefa' disabled>Add</button>
<button id='remover-selecionado' disabled>Remove Selected</button>
<ol id='lista-tarefas'></ol>
You were unnecessarily adding an event listener to each item in the list.
You can check the updated fiddle here: https://jsfiddle.net/msa9v2nf/
Since you're already checking which target element is clicked, there isn't any need to add an individual listener to each child item in the list.
I updated the umClick function:
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
listas.forEach((j) => j.classList.remove('selected'));
event.target.classList.add('selected');
});
}
}
The problem is you call the function umClick and call the function to add .selected within a click event in the same function umClick.
What happens is the click event completedLine.addEventListener('click', umClick); happens before the i.addEventListener('click', function semNomeDois() event. This is why you need a first click on the ol tag for only the first time.
To fixes this you have multiple options:
instead of calling click event on ol tag you can call mousedown which happens before click event.
Calling a click event on the li elements on creation, which needs a new function.
Depending on Vektor's answer, you can remove the unnecessary click event inside the first click event.
Also, I've made the red highlight on the .selected class instead of :focus, just to make it clear when the item is selected.
.selected {
background: red;
}
First Solution
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
const completedLine = document.querySelector('ol');
function umClick(event) {
if (event.target.tagName === 'LI') {
const listas = document.querySelectorAll('.lista');
listas.forEach((i) => {
i.addEventListener('click', function semNomeDois() {
listas.forEach((j) =>{
if(j != event.target)
j.classList.remove('selected');
});
this.classList.add('selected');
});
});
}
}
completedLine.addEventListener('mousedown', umClick);
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.selected {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
Second Solution
const textoTarefa = document.getElementById('texto-tarefa');
const criarTarefa = document.getElementById('criar-tarefa');
const listaTarefas = document.getElementById('lista-tarefas');
criarTarefa.onclick = function click() {
const lista = document.createElement('li');
lista.className = 'lista';
lista.id = 'lista';
lista.tabIndex = '0';
lista.innerHTML = textoTarefa.value;
listaTarefas.appendChild(lista);
lista.addEventListener('click',function(){
itemClick(this);
});
document.body.appendChild(listaTarefas);
textoTarefa.value = '';
};
function itemClick(item) {
const listas = document.querySelectorAll('.lista');
listas.forEach((j) =>j.classList.remove('selected'));
item.classList.add('selected');
}
function removeSelected() {
// teste
const listaSelected = document.querySelectorAll('.selected');
for (let i = 0; i < listaSelected.length; i += 1) {
listaSelected[i].remove();
}
}
.selected {
background: red;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css'>
</head>
<body>
<header>
<h1>My List</h1>
</header>
<input id='texto-tarefa' type="text" />
<button id='criar-tarefa' type="submit" onClick='click()'>Add</button>
<ol id='lista-tarefas'>
</ol>
<button id='remover-selecionado' type="submit" onClick='removeSelected()'>Remove Selected (Only One)</button>
<script src="script.js"></script>
</body>
</html>
I am not fully understand your problem but,
If you want to add the style when selecting a item, just add the style to
.selected
If you want in focus, and remove the class when there is no focus, you may add an eventlistener to control that.
I and my course mate are trying to write a code where when the order button is clicked it should save on local storage and redirect to an order page.
So far when we click on order it is not registered in the application/local storage section of the google developer tool and thus does not redirect to a new page.
We put an eventlistener to show a console.log for when we click, just to be sure the buttons are in order(this part is not important).
We also used an online javascript validator to eliminate typos and errors.
Also do we need any specific code on the order.html file to interface with local storage?
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>grc</title>
<link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>
<header>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</header>
<main>
<aside><img class="imgclass1" src="images/rounded logo.png" alt="Grocer Nigeria"></aside>
<article class="preinventory">
<section class="columns-desktop">
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="Desc"> Our Tomato2</p>
<button data-order="Tomato2">Order</button>
</div>
<div class="inventory">
<img class="sales" src="images/tomato.jpg" alt="Tomato"/>
<div class="columns">
<div class="title">Tomato</div>
<div class="Price">$100</div>
</div>
<p class="desc"> Our Tomato</p>
<button data-order="Tomato">Order</button>
</div>
</section>
</article>
</main>
<footer>
<nav>
<ul>
<li>Home</li>
<li>Groceries</li>
<li>Contact</li>
</ul>
</nav>
</footer>
<script type="text/javascript">
window.addEventListener("DOMcontentLoaded", function(e){
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click",function(e){
const button= e.currentTarget;
const container= button.parentNode;
const order={
id:button.getAttribute("data-order"),
title: container.querySelector(".title").innerText,
price1: container.querySelector(".Price").innerText,
desc:container.querySelector(".desc").innerText
};
localStorage.setItem('order', JSON.stringify(order));
const url = window.location.href.replace("grc.html","order.html");
window.location.href = url;
});
});
});
window.addEventListener("DOMcontentLoaded", function(e){
console.log("The page is loaded.");
});
const orderButtons= document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button){
button.addEventListener("click", function(e){
console.log("The button was clicked.");
});
});
</script>
</body>
</html>
**Below is what I see when I run the live server**
<!-- Code injected by live-server -->
<script type="text/javascript">
// <![CDATA[ <-- For SVG support
if ('WebSocket' in window) {
(function() {
function refreshCSS() {
var sheets = [].slice.call(document.getElementsByTagName("link"));
var head = document.getElementsByTagName("head")[0];
for (var i = 0; i < sheets.length; ++i) {
var elem = sheets[i];
head.removeChild(elem);
var rel = elem.rel;
if (elem.href && typeof rel != "string" || rel.length == 0 || rel.toLowerCase() == "stylesheet") {
var url = elem.href.replace(/(&|\?)_cacheOverride=\d+/, '');
elem.href = url + (url.indexOf('?') >= 0 ? '&' : '?') + '_cacheOverride=' + (new Date().valueOf());
}
head.appendChild(elem);
}
}
var protocol = window.location.protocol === 'http:' ? 'ws://' : 'wss://';
var address = protocol + window.location.host + window.location.pathname + '/ws';
var socket = new WebSocket(address);
socket.onmessage = function(msg) {
if (msg.data == 'reload') window.location.reload();
else if (msg.data == 'refreshcss') refreshCSS();
};
console.log('Live reload enabled.');
})();
}
// ]]>
</script>
</body>
</html>
The issue here is that the event DOMContentLoaded does not fire.
Here is how I have used the load event instead; for redirection, I have simply used URL search params (because I don't know what your other html file looks like) although you may use your other html document instead.
The snippet is below
However note: Stackoverflow will not allow the JavaScript to run, and will throw a securityError. To run this code you must save it on your computer or use a jsFiddle
function continue_ordering() {
alert("Now continue with order");
};
window.addEventListener("load", function(e) {
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
const button = e.currentTarget;
const container = button.parentNode;
const id = button.getAttribute("data-order");
const order = {
id,
title: container.querySelector(".title").innerText,
price1: container.querySelector(".price").innertext,
desc: container.querySelector(".desc").innerText
};
localStorage.setItem("order-" + id, JSON.stringify(order));
window.location.search = "?ordering=true&order-id=" + id;
});
});
});
window.addEventListener("load", function(e) {
if (window.location.search.search("ordering=true") != -1) {
console.log("User is ordering");
const params = new URLSearchParams(location.search)
const id = params.get("order-id");
if (!id || id == null) throw "There is no order id, error. Remove the ?ordering=true from the url and try again.";
const order_info = JSON.parse(localStorage.getItem("order-" + id));
if (!order_info) throw "Order information is not present: try ordering again. Remove the ?ordering=true from the url";
console.log("Order info is:\n", order_info);
document.getElementById("ordering").removeAttribute("hidden");
return;
};
document.getElementById("make-order").removeAttribute("hidden");
});
const orderButtons = document.querySelectorAll("button[data-order]");
orderButtons.forEach(function(button) {
button.addEventListener("click", function(e) {
console.log("The button was clicked.");
});
});
<div id="make-order" hidden>
<button data-order="test">Order</button>
<div class="title">This is the title</div>
<div class="price">130 USD</div>
<div class="desc">Lorem</div>
</div>
<div id="ordering" hidden>
<h1>
You are ordering.
<br> Choose
Stop ordering Or Continue with order
</h1>
</div>
The DOMcontentLoaded event has already fired by the time that code hooks it.
Check this post;
Code inside DOMContentLoaded event not working
Firstly I know I can make things a lot easier by creating the ul in HTML. I'm not supposed to be doing that.
My HTML:
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body id="body">
<form id="form" >
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>
</html>
My Javascript so far:
// Creating Array
var listData = ["Crab","Lobster","Scallops"];
// Creating initial List
function listFunction(){
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML+=element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
document.getElementById('ulId').appendChild(newLi);
newLi.innerHTML=input;
}
var liImg = document.getElementsByTagName('li');
for (var i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseover', handlerFunction, false);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src","https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height","10");
img.setAttribute("width", "10");
document.getElementsByTagName('li').innerHTML += "img";
}
So what I'm supposed to be doing is first create a list using the listData array, and displaying it on the page. Then I take the user input and add it to the list. This part is working fine
The part I am stuck on is having to create/display an image next to each list item when it is mouseover'ed. Then having to delete that specific list item if the image is clicked. I've created the eventListener, but the img part doesn't seem to be working.
The problem is when you're appending the image to the li element.
Solution:
e.target.appendChild(img);
// Creating Array
var listData = ["Crab", "Lobster", "Scallops"];
// Creating initial List
function listFunction() {
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element) {
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML += element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
document.getElementById('ulId').appendChild(newLi);
newLi.innerHTML = input;
}
var liImg = document.getElementsByTagName('li');
for (var i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseover', handlerFunction);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src", "https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height", "10");
img.setAttribute("width", "10");
e.target.appendChild(img);
}
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body id="body">
<form id="form">
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>
</html>
Hope this helps!
img is not string, it is a variable, so remove the surrounding double quotes from that. Since img is a node element, instead of using innerHTML you should use appendChild(). You also should use the e.target to refer the specific li element:
Change:
document.getElementsByTagName('li').innerHTML += "img";
To
e.target.appendChild(img);
I will suggest you to use mouseenter instead of mousemove. I think you need to attach the mouseleave event as well. You also have to attach the events to the newly created li elements.
Try the following way:
// Creating Array
var listData = ["Crab","Lobster","Scallops"];
// Creating initial List
function listFunction(){
var ul = document.createElement("ul");
ul.id = 'ulId';
document.getElementById('body').appendChild(ul);
listData.forEach(liFunction);
function liFunction(element){
var li = document.createElement('li');
ul.appendChild(li);
li.innerHTML+=element;
}
}
listFunction();
// Adding user input to the list
function inputFunction() {
var input = document.getElementById("userInput").value;
listData.push(input);
var newLi = document.createElement("li");
newLi.addEventListener('mouseenter', handlerFunction, false);
newLi.addEventListener('mouseleave', removeImage, false);
document.getElementById('ulId').appendChild(newLi);
newLi.insertAdjacentHTML('beforeend', input);
}
var liImg = document.getElementsByTagName('li');
for (let i = 0; i < liImg.length; i++) {
liImg[i].addEventListener('mouseenter', handlerFunction, false);
liImg[i].addEventListener('mouseleave', removeImage, false);
}
function handlerFunction(e) {
var img = document.createElement("img");
img.setAttribute("src","https://cdn1.iconfinder.com/data/icons/nuove/128x128/actions/fileclose.png");
img.setAttribute("height","30");
img.setAttribute("width", "30");
img.addEventListener('click', function(){
this.closest('li').remove();
});
e.target.appendChild(img);
}
function removeImage(e){
e.target.querySelector('img').remove();
}
<body id="body">
<form id="form" >
<input id="userInput" placeholder="Enter your list item here">
<button type="button" onclick="inputFunction()">Add</button>
</form>
<script src="A4.js"></script>
</body>
I made a chrome extension where my popup button calls a script. The other script uses jQuery but I get an error saying jQuery is not defined.
My popup.html:
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
My popup.js:
document.addEventListener('DOMContentLoaded', function() {
var login = document.getElementById('record');
login.addEventListener('click', function() {
chrome.tabs.executeScript({file: 'markStudents.js'});
});
});
myScript.js:
var arrays = []
$.get('Attendance.txt', function(data){
var splitted = data.split("\n"); // --> should return an array for each line
// Loop through all lines
for(var i = 0; i < splitted.length; i++)
{
var line = splitted[i];
// Now you could remove [ and ] from string
var removed = line.replace('[','').replace(']','');
var refined = removed.replace(' ', '');
// Now you can split all values by using , delimiter
var values = refined.split(',');
var array = [];
// Now you can iterate through all values and add them to your array
for(var c = 0; c < values.length; c++)
{
var value = values[c];
array.push(value);
}
arrays.push(array);
}
});
var present = arrays[0];
console.log(present);
var absent = arrays[1];
console.log(absent);
var user = present[0];
var pass = absent[0];
var loginField = document.getElementById('fieldAccount');
var passwordField = document.getElementById('fieldPassword');
loginField.value = user;
passwordField.value = pass;
var loginForm = document.getElementById('btn-enter-sign-in');
Is there any way to include my jquery.js in myScript.js?
Console Error
Just import jquery before you import popup.js
Like this
<!DOCTYPE html>
<html>
<head>
<title>HomAttendance</title>
</head>
<body>
<h1 style="color:#E54E4E">Hom<span style="color:#4E97E5">Attendance</span></h1>
<button type id="record" style="background-color:White"><h1 style="color:Black">Record Attendance</h1></button>
</body>
<script src="jquery-3.4.1.min.js"></script>
<script src="popup.js"></script>
</html>
Inside Your popup.js, when you load markStudents.js which uses jQuery, you'd again have to load jQuery before same
Like this
document.addEventListener('DOMContentLoaded', function () {
var login = document.getElementById('record');
login.addEventListener('click', function () {
chrome.tabs.executeScript(null, { file: "jquery-3.4.1.min.js" }, function () {
chrome.tabs.executeScript(null, { file: "markStudents.js" });
});
});
});
Just reorder your script tags and put jQuery before your popup.js. That way it will be loaded when you try to call it.
yo can use this code to include another jquery file in your jquery:
$.getScript("file address");
like this:
$.getScript("/assets/pages/scripts/ui-blockui.min.js");
I am trying to print the text multiple files in html. I succeeded in printing the single file. But I am unable to print the text output of a multiple files. Can you please help me in correcting the code?`
<!DOCTYPE html>
<html>
<body>
<h1> Testing programs </h1>
<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
<script type="text/javascript">
function readMultipleFiles(evt) {
//Retrieve all the files from the FileList object
var files = evt.target.files;
if (!files) {
for (var i=0, f; f=files[i]; i++) {
var r = new FileReader();
r.onload = (function(f) {
return function(e) {
var contents = e.target.result;
displayContents(contents);
};
});
r.readAsText(f);
}
} else {
alert("Failed to load files");
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML = contents;
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false)
</script>
</body>
</html>`
There is no need to use closure in provided snippet. As suggested by gurvinder, use innerHTML +=
if condition should be like if (files) as it will be true if length of files is greater than 0
Try this:
function readMultipleFiles(evt) {
var files = evt.target.files;
if (files) {
for (var i = 0; i < files.length; i++) {
var r = new FileReader();
r.onload = function(e) {
var contents = e.target.result;
displayContents(contents);
};
r.readAsText(files[i]);
}
} else {
alert("Failed to load files");
}
}
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML += contents;
}
document.getElementById('fileinput').addEventListener('change', readMultipleFiles, false);
<h1> Testing programs </h1>
<input type="file" id="fileinput" multiple />
<pre id="file-content"></pre>
<h3>Contents of the file:</h3>
Also refer this fiddle : https://jsfiddle.net/rayon_1990/2cwr4c00/
just replace the displayContents method as
function displayContents(contents) {
var element = document.getElementById('file-content');
element.innerHTML += contents; //observe + before =
}
since it needs to append the files rather than replace the last one