Reputation: 39
I have a group of inputs of the file type and I need to display the filename in multiple "p" elements when just one of the inputs is given a file. I have already tried to make it work with arrays but it won't function when I try that either.
HTML
<input type="file" accept=".doc" id="fileUpload1">
<input type="file" accept=".doc" id="fileUpload2">
<p class="paragraph">Select your file.</p>
<p class="paragraph">Select your file.</p>
JS
document.getElementById('fileUpload1').onchange = function () {
var file = document.getElementById('fileUpload1').value;
var filename = file.substring(file.lastIndexOf("\\") + 1);
var pr = document.getElementsByClassName("paragraph");
pr.innerHTML = "Selected File: " + filename;
};
Upvotes: 0
Views: 466
Reputation: 1203
First of all, each element must have a unique id
. Use class
if you want to refer to multiple elements.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
<script src="index.js"></script>
</head>
<body>
<input type="file" class="file-input" />
<input type="file" class="file-input" />
<p class="file-name">Select a file</p>
<p class="file-name">Select a file</p>
</body>
</html>
window.onload = function () {
var inputs = document.querySelectorAll('.file-input');
var paragraphs = document.querySelectorAll('.file-name');
for (var i = inputs.length - 1; i >= 0; i--) {
inputs[i].addEventListener('change', displayName);
}
function displayName(e) {
var file = e.target.files[0];
if (!file) return;
for (var i = paragraphs.length - 1; i >= 0; i--) {
paragraphs[i].innerText = file.name;
}
}
}
Upvotes: 1