I'd like to create a dropdown menu and display all the files currently in a directory so when the user clicks on an item in that list of files, it prints to console the name of that file.
Here is what I've come up with so far:
HTML
<form method="post">
<select name="DropdownList">
<option value="file1">fileArray[0]</option>
<option value="file2">fileArray[1]</option>
<option value="file3">fileArray[2]</option>
<option value="file4">fileArray[3]</option>
</select>
</form>
The problem with doing this hardcoded is what if there are 10 files instead of 4? Trying to figure a more dynamic approach.
Javascript
document.getElementByName('DropdownList').addEventListener('click', function() {
window.update.forEach(function(d, 'data/baselinedata') {
var f = readStringFromFileAtPath(d);
console.log(f)
});
});
function readStringFromFileAtPath (pathOfFileToReadFrom) {
var request = new XMLHttpRequest();
request.open("GET", pathOfFileToReadFrom, false);
request.send(null);
var returnValue = request.responseText;
return returnValue;
}
I guess I just don't know how to make this to dynamic instead of hardcoding the names in the list. I'm kind of a noob to web programming
Edit:
Just for clarity, all I want to do is populate a dropdown list with the names of files in a directory. So when a user goes to click an item in that list, it will print or log (via console.log()) the contents of that file.
You can use <input type="file"> element with multiple attribute set, create two arrays containing File object and result of FileReader.readAsText() and File objects iterate FileList object at change event of input type="file" element to set .name at <option> element .textConten, .value to index of uploaded File append to <select> element, set .value of <textarea> element to selected option which corresponds to index of File as text within array
<input type="file" multiple><br>
<select></select><br>
<textarea></textarea>
<script>
const [input, select, textarea, reader] = [
document.querySelector("input[type=file]")
, document.querySelector("select")
, document.querySelector("textarea")
, new FileReader
];
let [files, data, fn] = [
[],
[], (file, reader) => new Promise((resolve, reject) => {
reader.onload = () => {
reader.onload = reader.onerror = null;
resolve(reader.result);
}
reader.onerror = reject;
reader.readAsText(file);
})
];
input.onchange = async() => {
select.innerHTML = "";
files.length = data.length = 0;
for (const file of input.files) {
const {
name
} = file;
const option = new Option(name, files.length);
files.push(file);
select.appendChild(option);
let result = await fn(file, reader);
data.push(result);
}
}
select.onchange = () => {
textarea.value = data[select.value];
}
</script>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With