Is there a way to enhance this Java script file reader into a multi-file reader?

I am seeking assistance with JavaScript as it is not my strong suit, but I require it for my website. My goal is to be able to read the files that I select.

Below you can find the input form:

<form name="filUpload" action="" method="post" enctype="multipart/form-data">
    <div class="form-group">
        <label for="name">Name</label>
        <input type="text" name="name" id="name" class="form-control" value="" placeholder="Name">
    </div>
    <div class="form-group">
        <label for="Top">Top</label>
        <input onchange="readURL(this, '#thumbnail-Top');" class="form-control-file" type="file" name="userfile">
    </div>
    <div class="form-group">
        <label for="Bottom">Bottom</label>
        <input onchange="readURL(this);" class="form-control-file" type="file" name="userfile">
    </div>
    <div class="form-group">
        <label for="Left">Left</label>
        <input onchange="readURL(this);" class="form-control-file" type="file" name="userfile">
    </div>
    <div class="form-group">
        <label for="Right">Right</label>
        <input onchange="readURL(this);" class="form-control-file" type="file" name="userfile">
    </div>
    <div class="input-group">
        <input type="submit" style="" class="btn btn-success m-3" value="Submit" name="btn_type_send" />
    </div>
</form>

Next, we have the section where the selected pictures are displayed. The "id="thumbnail-..." is referenced in the script below. There seems to be an issue within this script which I will elaborate on shortly.

<div class="">
   <div class="card m-2">
       <h4 class="card-header text-center">Images</h4>
       <div class="d-flex">
           <div class="flex-fill">
               <h5 class="card-header">Top</h5>
               <div class="card-body">
                   <img class="card-img text-center" alt="" id="thumbnail-Top" src="#" style=""/>
               </div>
           </div>
   
           <div class="flex-fill">
               <h5 class="card-header">Bottom</h5>
               <div class="card-body">
                   <img class="card-img text-center" alt="" id="thumbnail-Bottom" src="#" style=""/>
               </div>
           </div>
           
           ...
       </div>
   </div>
</div>

Now comes the script part. I suspect that my challenge lies in selecting multiple IDs, which currently eludes me. I aim to pick one image for each category - "Top, Bottom, Left, Right". Additionally, I also wish to implement this functionality on another page with only three categories due to similar sides.

The #thumbnail refers to the specific ID mentioned earlier.

<script type="text/javascript">
    function readURL(input, id) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();
            reader.onload = function (e) {
                $(id).attr('src', e.target.result);
            }
            reader.readAsDataURL(input.files[0]);
        }
    }
</script>

Any examples or guidance would be greatly appreciated!

Answer №1

Response provided by @misorude

The correct input for onchange="readURL();" should look like this:

<form name="filUpload" action="" method="post" enctype="form-data">
                    <div class="form-group">
                        <label for="name">Name</label>
                        <input type="text" name="name" id="name" class="form-control" value="" placeholder="Name">
                    </div>
                    <!-- Image upload start -->
                        <div class="form-group">
                            <label for="top">Top image</label>
                            <input onchange="readURL(this, '#thumbnail-Top');"  class="form-control-file" type="file" name="userfile" id="file" />
                        </div>
                        <div class="form-group">
                            <label for="bottom">Bottom image</label>
                            <input onchange="readURL(this, '#thumbnail-Bottom');"  class="form-control-file" type="file" name="userfile" id="file" />
                        </div>
                        <div class="form-group">
                            <label for="left-side">Left side</label>
                            <input onchange="readURL(this, '#thumbnail-Left');"  class="form-control-file" type="file" name="userfile" id="file" />
                        </div>
                            <label for="right-side">Right side</label>
                        <div class="form-group">
                            <input onchange="readURL(this, '#thumbnail-Right');"  class="form-control-file" type="file" name="userfile" id="file" />
                        </div>
                    </div>
                    <!-- Image upload end -->
                    <div class="input-group">
                        <input type="submit" style="" class="btn btn-success m-3" value="Submit" name="btn_type_send" />
                    </div>
                </form>

The section where the image is displayed appears as follows "it's not really styled".

<div class="card m-2">
       <h4 class="card-header text-center">Images</h4>

                <div class="d-flex">
                    <div class="flex-fill">
                    <h5 class="card-header">Top</h5>
                        <div class="card-body">
                            <img class="card-img text-center" alt="" id="thumbnail-Top" src="#" style=""/>
                        </div>
                    </div>

                    <div class="flex-fill">
                    <h5 class="card-header">Bottom</h5>
                        <div class="card-body">
                            <img class="card-img text-center" alt="" id="thumbnail-Bottom" src="#" style=""/>
                        </div>
                     </div>

                    <div class="flex-fill">
                    <h5 class="card-header">Left</h5>
                        <div class="card-body">
                            <img class="card-img text-center" alt="" id="thumbnail-Left" src="#" style=""/>
                        </div>
                    </div>

                    <div class="flex-fill">
                    <h5 class="card-header">Right</h5>
                        <div class="card-body">
                            <img class="card-img text-center" alt="" id="thumbnail-Right" src="#" style=""/>
                        </div>
                    </div>

                </div>

       </div>

The script has been updated with the corrected readURL function and $(id) references.

<script type="text/javascript">
function readURL(input, id) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
        $(id).attr('src', e.target.result);
    }
        reader.readAsDataURL(input.files[0]);
    }
}

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

Transform a JSON array containing individual objects into a new JSON array with objects

My array contains objects with nested objects in each element, structured like this: [ { "person": { "name": "John", "isActive": true, "id": 1 } }, { "person": { "name": "Ted", "isActive": true, "id": 2 } } ] I ...

Tips for retrieving javascript-generated HTML content

Currently, I'm attempting to retrieve article headlines from the NY Times website. Upon inspection, it appears that the HTML is being generated by Javascript since it's only visible when using the 'inspect element' feature in Firefox. ...

Retrieving JSON data via an AJAX call

Similar Question: Sending PHP json_encode array to jQuery I've created a function that searches a database for a specific name using $.post. It returns user details with matching search criteria in JSON format generated by PHP, like this: Arra ...

Vue messaging application fails to display data upon mounting

Recently, I've been experimenting with different Vue chat libraries and encountered this interesting piece of code: <template> <p>{{ this.users[0] }}</p> </template> <script> export default { data() { return ...

How to resolve a Cross-Origin Resource Sharing (CORS) error when trying to access a local JSON file

Currently, I am attempting to use vanilla JS AJAX request in order to retrieve a JSON string from a locally stored JSON file. My main objective is to accomplish this without relying on JQuery. The code snippet below was inspired by this answer. Despite my ...

Exploring IP geolocation integration within Rails 3

I am looking to add a dynamic feature to my homepage that will display the location object closest to the reader's physical location. Currently, I have a Location model with longitude and latitude fields. My goal is to retrieve the location model obj ...

Running a JavaScript function within a designated div element

I'm currently facing an issue with executing a javascript function - onload only in a specific div. I seem to be stuck on this problem, so if anyone could offer some assistance, I would greatly appreciate it. Thank you very much in advance! functio ...

The JSON GET method displays HTML content when accessed through code or console, but presents a JSON object when accessed through a web address

I am currently trying to execute the following code: $(document).ready(function () { $.ajax({ url: 'http://foodfetch.us/OrderApi/locations', type: 'GET', success: function(data){ alert(data); ...

Strategies for transferring data from index.html to component.ts in Angular 4

Greetings, as a newcomer to Angular, I am seeking advice on how to link my Index.html file to component.ts. Please review the code snippet below where I have created a function called scannerOutput in my Angular index.html file which is functioning properl ...

Animate the transition effect as soon as the block is displayed

Looking to create a smooth page transition using CSS changes with the help of Javascript (jQuery). Initially, one of the pages is set to display none. page1 = $('.page1'); page2 = $('.page2'); page1.removeClass('animate').cs ...

Creating a Dynamic Form with jQuery, AJAX, PHP, and MySQL for Multiple Input Fields

Success! The code is now functional. <form name="registration" id="registration" action="" method="post"> <div id="reg_names"> <div class="control-group"> <label>Name</label> <div class= ...

Attempting to use insertAdjacentHTML on a null property results in an error

I keep encountering the same error repeatedly... Can someone please explain what's going wrong here and provide a hint? Error script.js:20 Uncaught TypeError: Cannot read property 'insertAdjacentHTML' of null at renderHTML (script.js:20) a ...

Ways to retrieve an input field value without triggering form submission

I'm currently working on a payment form where users input the amount in a text field. I also have another text field on the same form that should automatically display the amount in words based on the user input. However, I'm struggling to figure ...

The search functionality in the table is experiencing a glitch where it does not work properly when trying to search with a

I created a simple mini-app with a search bar and a table displaying data. Users can enter keywords in the search bar to filter the data in the table using lodash debounce function for smoother performance. Everything works fine except for one issue - when ...

Animating numerous elements simultaneously during Vue component rendering

Take a look at this simple case in the following jsfiddle: https://jsfiddle.net/hsak2rdu/ I attempted to swap and animate two elements, but it didn't work as expected. When you click the toggle button in the playground, the second element quickly mo ...

What is the best approach for extracting functions from express routes for unit testing?

I have a JavaScript controller containing some exported routes. I am interested in accessing the functions used within these routes for unit testing purposes. While many blogs suggest creating actual HTTP requests to test express routes, I consider this t ...

Guidance on redirecting and displaying the URL retrieved from an API response object in the browser using express and axios

Currently in the process of developing a payment gateway using the Paystack API along with Axios for managing HTTP requests. After thoroughly examining their API documentation and reviewing their Postman collection, I was able to grasp how to structure th ...

Utilize a jQuery selector to target the initial element of every alphabet character

I'm seeking some assistance with jQuery selectors and have a specific scenario that I need help with. Here is the HTML structure I am working with: <ul> <li class="ln-a"></li> <li class="ln-b"></li> <li cl ...

Transcribing live content directly from the browser tab

I have a unique idea for developing a browser extension specifically for Chrome. This extension would provide live transcriptions of my team's meetings directly from an open tab in the browser. I am interested in extracting keywords, such as my name, ...

I am looking to enhance my JSON output using JavaScript

My JSON output appears as follows: {"intent":"P&P_Purchase","value1":{"date1":"30-Dec-19","prd_desc":"NEEM UREA OMIFCO (45 KG)","qty":"18MT","inv_no":"NRKT07003160"},"value2":{"date1":"25-Dec-19","prd_desc":"NEEM UREA IMP (45 KG)","qty":"18MT","inv_no ...