Modify the jQuery code by replacing the class selector with the id selector

I have several input fields of type "file" that allow users to upload images. Previously, I had a script that worked with a single input and was created using a class selector. Now, as I need to work with multiple inputs, I tried changing the script by assigning IDs, but it's not functioning properly yet. Why is that?

function readURL(input) {
  if (input.files && input.files[0]) {

    var reader = new FileReader();

    reader.onload = function(e) {
      $('.image-upload-wrap').hide();

      $('.file-upload-image').attr('src', e.target.result);
      $('.file-upload-content').show();

      $('.image-title').html(input.files[0].name);
    };

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

  } else {
    removeUpload();
  }
}

function removeUpload() {
  $('.file-upload-input').replaceWith($('.file-upload-input').clone());
  $('.file-upload-content').hide();
  $('.image-upload-wrap').show();
}
$('.image-upload-wrap').bind('dragover', function () {
$('.image-upload-wrap').addClass('image-dropping');
});
$('.image-upload-wrap').bind('dragleave', function () {
$('.image-upload-wrap').removeClass('image-dropping');
});
body {
  font-family: sans-serif;
  background-color: #eeeeee;
}

// Rest of CSS code here...

</script><br />  
// HTML structure for file uploads goes here...

At the moment, when you upload an image, it shows up in all other input fields as well.

Answer №1

It's important to tailor your code to the specific container of the image you're working on. Currently, you may be inadvertently changing the appearance of all elements with the same class, resulting in them all looking the same.

Check out this demo - Fiddle

Here's an example of how to use the onload function:

reader.onload = function(e) {
   var $parent = $(input).parent(),
       $nextEl = $parent.next();

   $parent.hide();
   $nextEl.find('.file-upload-image').attr('src', e.target.result);
   $nextEl.show();
   $nextEl.find('.image-title').html(input.files[0].name);
};

For the removeUpload function, you can use this code:

function removeUpload(button) {
   var $parent = $(button).parent().parent();

   $parent.hide();
   $parent.prev().show();
}

Don't forget to update the onclick function call for the remove buttons to onclick="removeUpload(this)" so that the correct button is passed to the function.

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

Creating and sending HTML formatted emails using Django 1.7

The function send_mail() now accepts a new parameter - html_message. Check out the official documentation for more details. I have an email.html file and I need to send an html version of my message using Django 1.7. Can someone provide me with an example ...

How to place an element in a specific location within the DOM using JavaScript

How can I position a created element in a specific place within the DOM using this code? Currently, it appends at the bottom of the page. var x = document.getElementById('options_10528_1'); var pos = document.getElementById('options-10528- ...

I'm looking for some good .NET MVC frameworks that can help create dynamic AJAX applications

I am interested in developing applications with a dynamic user interface that utilizes ajax technology. Some key features I am looking for include: Automatic saving of user input in forms, even if the data is incomplete Realtime validation of form fields ...

No data found in AJAX session array

I am currently in the process of developing an ordering system that involves two distinct ways to add products. Both methods involve using an ajax request to insert products into the basket. The first method allows for direct addition of products with no a ...

Tips for retrieving text from an element that is nested within an element's promise in Appium

Here's a snippet of code I'm working with: const wd = require('wd') const driver = await wd.promiseChainRemote("http://localhost:4723/wd/hub") elements = await driver.elementsByAccessibilityId("commonElementsId") I have received a pro ...

Ensuring Angular2 Javascript is validating only numerical input and not accepting characters

Access the full project here (excluding nodes_modules): Note: After running the project, all actions related to this issue can be found in the "Edit All" section of the website. Click on that to view the table. The main objective of this website section ...

`Showcasing the present link in the navigation bar`

Is there a way to easily highlight the current category on the navigation bar? Any guidance on how to accomplish this would be greatly appreciated. Thanks in advance. ...

Analyzing vast datasets from contrasting perspectives

Looking for a way to compare two different data storages that contain the same data. The data in question is: const object1 = { "name": "John", "age": "30", "height": "180 cm", "stand ...

Display and conceal interactive jQuery UI Dialogs

Despite its seemingly simple nature, I'm encountering some challenges with my current approach. My goal is to dynamically generate jQuery UI dialogs for the "help" element. The desired functionality is to toggle the visibility of the dialog when clo ...

Encountering unexpected behavior with the .data() method

I'm encountering an issue with my code <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv= ...

How can I correctly export my npm package?

I have successfully developed an npm package. class Person { constructor() {} sayHello() {console.log("Hello World!")} } module.exports = Person; Upon installing the package using npm i my-package, it was integrated into my project. ...

Guide on uploading a file using Node.js

Here is an example of HTML code: <html> <body> <form action="http://localhost:3000/api" method="post" enctype="multipart/form-data"> <input type="file" name="file"> <input type="submit"> </form> </body> &l ...

JQuery could not retrieve the property 'json' from an undefined or null reference

Currently, I am in the process of developing a Windows 8 app using HTML and accessing data from an API. Unfortunately, I keep encountering an error: 0x800a138f - JavaScript runtime error: Unable to get property 'json' of undefined or null refer ...

MongoDB Sorting Techniques

I'm struggling to figure out how to retrieve an ordered list from MongoDB data. I need to fetch the results from a Mongo collection using return and .find(), structured like this: For instance, let's say I have one collection for cars with 10 do ...

Limit the vertical movement in Vue drag and drop operations

Currently, I am working on a project that involves implementing drag-and-drop functionality using vue-draggable. You can find more information about it here: https://github.com/SortableJS/Vue.Draggable. I am facing an issue where the height of the element ...

Using JavaScript to create a tree structure with hierarchical organization in JSON

Having some trouble converting a nested hierarchical tree from a JSON array. Looking to create a hierarchical tree structure from the provided JSON data. Below is the data: [{ "_id" : "59b65ee33af7a11a3e3486c2", "C_TITLE" : "Sweet and Snacks", ...

Issue with fading in! The div should fade in only when it is no longer covering the element

I am currently working with two div elements called "#Header_Info" and "article". The "article" div is static and displays information on the page, while the "#Header_Info" div expands to show extra information. However, a problem arises when the "#Header ...

JavaScript failing to update variable with new value

Alright, so here's the situation. I'm working on a node.js file where I've got a function set up to search for a user in mongodb using specific fields. The goal is to retrieve their account value and then pass it along for further processing ...

The functionality of the window.location.href in an Asp.Net MVC application is not properly functioning on Google Chrome

Hey there! I'm facing an issue with jQuery concerning window.location.href in my ASP.NET MVC application. Here's what's going on: I have a grid view that utilizes Html.actionlink to make an AJAX request which deletes a row from the database. ...

Fetching Data Sequentially with a Delay using AJAX and jQuery in PHP

As a newcomer to Jquery, I am looking for a way to showcase data in a sequential manner using AJAX. Imagine there is a table called "DATA" in my database with a field named "info" containing multiple rows of information. info 1 2 3 4 5 My goal is to exh ...