Steps to make a dropdown menu that showcases all files within a folder using HTML5 and Javascript

I am attempting to implement a dropdown menu that displays all the files currently in a directory. The goal is for the user to be able to click on a file in the list and have the name of that file printed to the console.

Here is my current progress:

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 issue with this hardcoded approach is that it may not adapt well if there are more than 4 files. I am looking for a more dynamic solution.

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 am struggling to figure out how to dynamically generate the list of file names in the dropdown without hardcoding them. As a beginner in web programming, I find this challenging.

Edit:

To clarify, my objective is simply to populate a dropdown list with the names of files in a directory. When a user clicks on an item in the list, the contents of that file should be printed or logged using console.log().

Answer №1

To implement multiple file upload functionality, utilize the <input type="file> element with the multiple attribute enabled. Create two arrays to store the File objects and the results of reading these files using FileReader.readAsText(). Iterate through the FileList object upon a change event on the file input element to set the .name as the .textContent of an <option> element and assign the index of the uploaded file to its value, appending this option to a <select> element. Finally, set the value of a <textarea> element to display the text content corresponding to the selected file.

<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>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Functionality not functioning within Shadow DOM

After creating and exporting an Angular Element as a single script tag (user-poll.js), using the element on a host site is simple. Just include the following two lines: <user-poll></user-poll> <script src="path/to/user-poll.js"></sc ...

Retrieve data from multiple tables using knex.js

I am trying to use Express.js and knex.js to render data from two tables using only one GET function. I have successfully queried each table individually (schools or students), but I am unsure how to query both at the same time. Any ideas? app.get('/ ...

What is Flask's approach to managing JSON data?

I am currently developing an editable table using FLASK, JSON, and jQuery. After serializing the form, I send it via $.getJSON, as shown at the bottom of my JS code: This is the JS code: $(function(){ $('tbody').on('click', &apos ...

How can I repeatedly show text using knockout js?

How can I use KnockoutJS to display the text and year within a div loop when selecting a brand and model? Example: Mercedes>C *C-180 *2016 *C-200 *2015 Here is the HTML code: <select data-bind="options: manufacturers, optionsCaption:'Bra ...

Navigating to a different page on Vue2 with routes

I am struggling with redirecting to another Vue page from my script code. I tried using router.push() but it's not directing me to the desired Vue page. Here is a snippet of my source code: src/router/index.js import Vue from 'vue' import ...

What is the best way to incorporate a search feature within Bootstrap cards?

I've been struggling to incorporate a search feature within my bootstrap cards. Despite trying various online methods, none have proven successful for me so far. Below is my HTML code - any assistance in implementing a search filter into my app would ...

Exploring color options in matplotlib for HTML designs

Is there a way to change color in a matplotlib plot using html in Python? I attempted plt.plot(x,y,marker=".",color="#e0e0e0") However, this resulted in data points displayed as ".", connected by lines of color #e0e0e0 which is not desired. I also experi ...

Struggling to keep my image buttons aligned in a horizontal line at the center, but they keep stacking vertically instead

I'm struggling to keep a row of image buttons centered horizontally, regardless of the window size. However, when I manage to center the buttons, they end up stacking vertically instead of aligning in a single line. I've experimented with differ ...

Implementing line breaks in JSON responses in an MVC application

I am looking to show a JavaScript alert with line breaks using the message returned from a controller action that returns JSON result. I have included "\n" in the message for line breaks. Below is the code snippet from my controller: [HttpPost] publ ...

`The search bar and search button`

On mobile, I have a search field and a button working fine. However, when typing in something and hitting "search" on the phone's keyboard, it leads to a 404 error. But clicking the "search" button works as expected. I would like to be able to hit "se ...

How to Transfer Data from SuperAgent Library Outside the .then() Block?

I have a dilemma in my Nodejs project with two interdependent files. The key to this issue lies in the usage of a crucial library known as SuperAgent (I need it) Check out SuperAgent Library Here In file1.js const file2 = require('./file2'); ...

What sets apart the Jquery Function Template from the Method Template?

Can someone explain the difference between Jquery Function Templates and Method Templates and how to properly utilize them? Below is a snippet of a Function Template and Method Template, but what sets them apart? Function Template:- (function($){ $.f ...

Fade effect not working with Bootstrap Modal

I am encountering an issue with the Twitter Bootstrap modal while trying to display post details on WordPress. The problem is that when the modal opens, the entire screen turns grey and nothing in the modal is clickable. I can only exit this mode by pressi ...

The PHP DOM feature is inserting an additional <p> element along with <html> and <body> tags

When it comes to displaying different images for desktop and mobile users based on their device, I have implemented a function in my index.php file. The code snippet from my index.php file: <!DOCTYPE html> <html class="no-js" lang="en"> <h ...

Tips for dynamically loading images as needed

I'm working on a simple image zoom jQuery feature using elevateZoom. You can see a Demo example here. The implementation involves the following code: <img id="zoom_05" src='small_image1.png' data-zoom-image="large_image1.jpg"/> <sc ...

Is there a way to utilize jQuery's load function to fetch just a single element rather than the entire webpage?

I am looking to make a slight modification to the function so that it only loads the content of the colTwo div from the selected link on the menu, instead of loading the entire page. After checking out the code snippet on the jQuery website: $('#resu ...

Tips for formatting a lengthy SQL query in a Node.js application

Currently, I am facing a challenge with a massive MySQL select query in my node.js application. This query spans over 100 lines and utilizes backticks ` for its fields, making me uncertain if ES6's multi-line string feature can be used. Are there any ...

Failure to trigger success or error callbacks in Angular's $http.get request

Trying to access the nutritionix v1_1 API through a get request has been a bit tricky. Despite the function being called successfully and passing the correct data, the $http.get request seems to be causing some trouble. It simply skips over the remaining c ...

Running npm build/deploy is not functioning properly and is throwing a "failed to compile errors" message

I attempted to use npm run deploy/build, but it was unsuccessful and resulted in an error in the terminal. As a novice in git and github, I am looking to upload the changes I made in my most recent commit to my github pages. However, no matter how many tim ...

"Create a sleek slider with a modern Apple store aesthetic using Javascript

While I am willing to put in some effort, I am a bit lost at the moment. I am attempting to create a slider similar to the one featured on the home section of the Apple website. How can I enable a click on an image to navigate through slides? Alternatively ...