Tap on the image placeholder to replace it with your own image

Just starting out, I have the following HTML code within a <form>:

<div class="image-upload">
 <img id="send_photo_img1" src="assets/images/index2.png"/>
 <input id="send_photo_input1" type="file"/>
 <img id="send_photo_img2" src="assets/images/index2.png"/>
 <input id="send_photo_input2" type="file"/>
</div>

The goal is to allow users to click on the image (index2.png) with a "+" sign as a placeholder, which would then open a window like an input=file, allowing the user to choose an image to replace the placeholder.

Here is the rest of the code:

Jquery function inspired by @Ivan Bayev's answer here:

function readURL(input) {

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

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

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

$("#send_photo_img1").click(function(){
    $("#send_photo_input1").trigger("click");
    $("#send_photo_input1").change(function(){
        readURL(this);
    });         
});

CSS styling:

.image-upload > input
{
    display: none;
}

While the code works, I'm not completely satisfied with (1) the use of jQuery and (2) the loading time once the image replaces the placeholder. The "loading" sign remains for about 30-40 seconds before disappearing.

Any advice or suggestions are greatly appreciated. Thank you!

Answer №1

If you're looking for a solution to the problem mentioned earlier, look no further.

Firstly, it's not ideal to attach code to IDs when dealing with multiple instances of input=file on a single page. It's better to use classes instead. Each block should resemble this:

<div class="image_upload">
 <img class="upload_image" src="assets/images/picture.png"/>
 <input class="file_input" type="file"/>
</div>

Then, you'll need some jQuery workaround to select it:

$(".image_upload img").click(function(){
    var imageDiv = $(this).next(".file_input");
    imageDiv.trigger("click");
    imageDiv.change(function(){
        //console.log('Use this to track results');
        //your function goes here.
    });
});

CSS:

.image_upload input
{
    display: none; // hides the original input
}
.image_upload img
{
    width: 90px;
    height: 90px;
    cursor: pointer;
}

The ReadURL function in my query works perfectly well, just make this adjustment:

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

change to:

reader.onload = function (e) {
   $(input).prev(".upload_image").attr('src', e.target.result);
}

And remember, I'm using prev(), but you could opt for a more general approach:

 $(input).parent().find(".upload_image").attr('src', e.target.result);

Consider using an icon instead of an image for a better visual impact.

This response aims to provide you with a functional code snippet for the issue at hand. Don't hesitate to reach out for more details if necessary.

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

What is the best way to align the items in two lists at the center as if they were all individual

Q: How can I center the list-item elements of two unordered lists as if they were children of just one list? Example: {[1][1][1][1][2][2]} { [2][2] } CSS Alignment Challenge <div> <ul> &l ...

The functionality of using an Ajax call to invoke a php function on the same page is not functioning correctly

I am facing an issue where Ajax is not working in the same PHP file as the PHP function I want to call. My goal is to have a button that, when pressed, will trigger the function without reloading the page. I have placed my Ajax script at the bottom and the ...

Organizing data with Tablesorter and preserving the sorting order

My table contains valuable information that is initially generated from a PHP script and then updated every n-seconds by checking the database. To enhance the functionality of my table, I decided to install the tablesorter plugin. However, I encountered a ...

Maintain the basic structure while ensuring divs are properly aligned

Behold, my div structure! ONE // at the top level TWO THREE // two divs side by side in the middle level FOUR // residing at the bottom <div id="ONE"> <div></div> <div><img src="logo.png"></div> </div> < ...

What is the best way to customize the appearance of a non-current month cell within the date picker?

I'm currently in the process of developing a registration form for my JavaFX application. I am faced with an issue where I need to disable certain cells in the date picker when they do not belong to the displayed month. Let's take a look at my cu ...

Creating a professional HTML/CSS signature for optimal performance in Outlook 2016

For my email signature, I currently have an HTML coded design that includes a 400x415 dashed line with specific color specifications. However, Outlook Express 2016 is unable to display this element properly. Despite using inline CSS, it appears that CSS d ...

Creating a list of font sizes for each <p> tag in my HTML document

I am looking to create an array containing the font sizes of all the p tags in my HTML document. How can I specifically target only the p elements and not their parent elements? ...

Browsing through a jQuery JSON object in Chrome reveals a dynamic reshuffling of its order

Jquery + rails 4 Within the json_data instance, there is data with key-value pairs. The key is an integer ID and the value is an object containing data. However, when attempting to iterate over this data using the jQuery $.each function, the results are s ...

How can I load a specific div region using ajax for submitting a form?

I'm not sure if my approach is correct. On my main page, I have some information displayed. When you click a button, the form will load from a separate file: $('#viewport').load('/views/myView.php #targetDiv') This works fine ...

The Flot chart updates with a new data point appearing at the end whenever there is a change in

Incorporating the following flot chart directive: /**========================================================= * Module: flot.js * Initiates the Flot chart plugin and manages data refresh =========================================================*/ (fu ...

What are the steps to resize a YouTube embedded video?

I am currently attempting to use a YouTube video as the background for breadcrumbs on my website. However, I am facing an issue with setting the video width to cover the full screen. The image below shows that the video is displayed in the center of the if ...

Sending a list of custom objects including images via AJAX to a REST API in a Spring Boot application

Encountering a problem with an Ajax call when passing a List of custom objects with images to a REST API in Spring Boot. Below is a snippet of my code. Controller @PostMapping(value = { "/test/saveUser" }, consumes = { "multipart/form-data& ...

Tips for implementing AJAX in the menu bar using PrimeFaces

Hey there, I was wondering something. Let's say I have a navigation bar like the one below: Navigation Bar Is there a way to use ajax or any other method so that when I click on a menu item or submenu in the navigation bar, the name of the menu item ...

Unable to pass a variable through ajax to another PHP file

I am currently facing an issue with passing a variable from one PHP file to another using ajax. In my 'index.php' file, there is a button that, when clicked, should pass the button's id to another PHP file named 'show_schedule.php' ...

Using a background image in CSS

I'm having an issue with this code. It doesn't seem to be displaying anything on the screen: <!DOCTYPE HTML> <head> <title> CSS(lab2) </title> <meta charset="UTF-8"> <style type = "text/css"> ...

Dynamically populate 7 select boxes with options using JQuery

I have a webpage that includes 14 different dropdown menus, one for each day of the week (Monday to Sunday). Each day has two dropdowns: one for opening time and one for closing time. I used jQuery to populate all 14 dropdowns with a pre-defined list of ho ...

Having trouble with sending POST data to server while trying to save to a JSON file using ajax and php

I attempted to follow the instructions from various stackoverflow posts, but it seems that my server is not acknowledging any incoming requests. I am certain that the client is sending the request because it can be seen in the Firefox debugger tool. Below ...

Steps to clear a form after submitting it

Hello all, I have a rather complex form that sends a message successfully with an alert after submission. I'm wondering how I can clear the entire form once it has been submitted to make it simple? Below is my HTML Form and JavaScript code. I would l ...

What is the best way to identify the differences between two non-unique arrays in JavaScript? I initially relied on underscore, but I am willing to

Given two arrays: firstArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}, {id:'id3'}] secondArray = [{id: 'id1'}, {id:'id2'}, {id:'id3'}] The expected output is [{id:'id3'}] This ...

The admin-ajax.php file in WordPress consistently fails to return any value other than

I developed a WordPress ajax plugin, but I am facing an issue where admin-ajax.php always returns 0 and the plugin doesn't work as expected. Here is the code I have implemented: add_action( 'wp_ajax_example_ajax_request', 'example_aja ...