Show an image sourced from a URL, and continue this process for a total of three pictures

I have been attempting to figure out a way to repeat the script so that I can display 3 photos on click and insert a URL. The code below successfully works for the first picture, but I am struggling to make it display the second picture. Currently, the URL populates the second input field but does not display any image.

<div class="form-group">
<label class="col-md-4 control-label" >Photo 1</label>

   <div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-camera pink"></i></span>
<form id="form1" runat="server">

    <input type='file' id="imgInp" />
    <img id="blah1" alt="Image Preview" width="247" height="142"/>
</form></div></div></div>


<script type="text/javascript">
  function readURL1(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah1').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        readURL1(this);
    });

</script>


<div class="form-group">
<label class="col-md-4 control-label">Photo 2</label>

   <div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-camera pink"></i></span>
<form id="form2" runat="server">

    <input type='file' id="imgInp2" />
    <img id="blah2" alt="Image Preview" width="247" height="142"/>
</form></div></div></div>

<script type="text/javascript">
  function readURL2(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah2').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp2").change(function(){
        readURL2(this);
    });

</script>

Answer №1

It appears that both photo1 and photo2 have the same id for form "form1", img "blah", and input "imgInp". This issue should be resolved by ensuring that all ids are unique across the entire page. Please assign different ids to all HTML elements.

Additionally, it is not recommended to blindly repeat scripts like that. It is better to reuse code where possible.

function readURL(input, imgID) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $(imgID).attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }
    
    $("#imgInp1" ).change(function(){
        readURL(this, "#blah1");
    });

    $("#imgInp2" ).change(function(){
        readURL(this, "#blah2");
    });
<div class="form-group">
<label class="col-md-4 control-label">Photo 1</label> 

   <div class="col-md-4 inputGroupContainer">
<div class="input-group">
<span class="input-group-addon" ><i class=" glyphicon glyphicon-camera pink  "></i></span> 
<form id="form1" runat="server">

    <input type='file' id="imgInp1" />
    <img id="blah1" id="#" alt="Image Preview" width="247" height="142"/>
</div></div></form></div>
<div class="form-group">
<label class="col-md-4 control-label">Photo 2</label> 

   <div class="col-md-4 inputGroupContainer">
<div class="input-group" >
<span class="input-group-addon"><i class="glyphicon glyphicon-camera pink"></i></span> 
<form id="form2" runat="server" >

    <input type='file' id="imgInp2" />

    <img id="blah2" id="#" alt="Image Preview" width="247" height="142"/>
</div></div></form></div>

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

Attempting to replace the checkbox image resulted in no changes

<?php require 'includes/configs.inc.php'; ?> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title><?php $site_name ?></titl ...

What is the best way to switch from using the three.js JSONLoader to the ObjectLoader?

I successfully loaded multiple files using the code below for three.js JSONLoader: <!DOCTYPE html> <html> <head> <title>Rotating Sphere</title> <meta charset="utf-8"> <!-- https://cdnjs.com/libra ...

Is there a way to transform inline JS coding to an external style sheet?

I currently have JavaScript code in both the body and head sections of my webpage. If I decide to move them to an external .js file, what steps should I take to transfer them and then bring them back onto the page? Head - <script language="Javascript ...

Go to a different webpage containing HTML and update the image source on that particular page

I am facing an issue with my html page which contains multiple links to another page. I need to dynamically change the image references on the landing page based on the link the user clicks. The challenge here is that the link is inside an iframe and trigg ...

Utilize the image button to transfer a picture from your desktop

I have created a table using HTML. The first cell of the table (1,1) contains an image that I want to function as a button. When the image is clicked, I would like to be able to select a photo from my computer and add it to the next available cell in the t ...

Google HTTP/REST OAuth: The authorisation code request contains a state parameter for the database user, while the access token request does not

I have successfully implemented the OAuth server flow for Google. The process begins with the user clicking a link that triggers javascript to open a popup containing a URI request, which is functioning perfectly: var endpoint = "https://accounts.google.c ...

What could be causing the issue of the title in req.body to display as 'undefined'?

I am currently learning about NODE JS and practicing working with POST forms from PUG to a NODE JS server. I am facing an issue where the submission input is coming back as 'undefined' when I submit a form from the web browser. In the code snipp ...

Floating Action Button is not properly attached to its parent container

When developing my React Js app, I decided to utilize the impressive libraries of Material UI v4. One particular component I customized is a Floating Action Button (FAB). The FAB component, illustrated as the red box in the image below, needs to remain p ...

Assign a class to the following element using an Angular 2 Directive

I have a dropdown menu and I want to incorporate an Angular2 directive to control the opening and closing of this dropdown. How can I apply the open class to the latest-notification div, knowing that my directive is applied to the button tag? Below is my ...

React native encountered an issue where an undefined object was being evaluated

Having trouble with my React Native shopping cart app that uses Redux undefined is not an object (evaluating 'this.props.items.length') I'm following a tutorial on React Redux to build the cart functionality, but I keep encountering this e ...

Should private members be kept confidential during program execution?

While Typescript's "private" members may not be truly private at runtime, traditional closures maintain the privacy of their members. Is there value in ensuring that private members remain private during runtime? ...

Transforming curl commands into ajax requests

I am trying to convert this curl request into AJAX format: curl -X GET --header 'Accept: application/xml' --header 'Authorization: Basic eGZlZG9yMDNAc3R1ZC5maXQudnV0YnIuY3o6YXVkZWxpdmVy' 'http://example.com/user' $.ajax({ typ ...

Tips for accessing information from a FOR loop within DIV tags

Let's explore the following code snippet: Here is the HTML generated: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>Website ...

Using node.js to import modules with relative paths

For my project structured following the MVC pattern, I have node.js modules in various directories. I need to use require to access modules located outside of the current directory. How can I achieve this? /app/controller/c1.js ... /app/model/m1.js ... ...

Error encountered: ReferenceError when using node.js, express, ejs, bcrypt,

Recently started diving into node.js and encountered an issue when trying to merge code from various projects. Everything was functioning smoothly until I switched the route path from '/dashboard' to '/store' along with the correspondin ...

Seamlessly replacing an image in PixiJS without any sudden movement

I'm currently developing a HTML5 JavaScript game with a heavily textured background. My goal is to incorporate a 3D background element that can be swapped out dynamically. For example, the initial scene may show a room with a closed door, but once a J ...

Divide the promised variable into separate named variables

Here is a code snippet that I am working with: Promise.all( categories.map(category => Collection.find({ category })) ).then(items => { return items }) Currently, the output is an array with the same length as categories, where each element is ...

Globalized Navigation in Next.js

Is there a way for Nextjs to automatically detect the user's country based on the cookies from Cloudflare and incorporate it into the URL? We want to personalize our site for specific countries without manually listing them all out in different langua ...

What is the most effective way to utilize zoom with an Orthographic projection?

I'm attempting to utilize THREE.OrbitControls for zooming in an orthographic projection, but I'm not achieving the desired outcome. I believe it may be possible to adjust the viewSize that is multiplied by left, right, top, and bottom to achieve ...