Display picture within a modal window, regardless of whether it is the identical image

I have a file input that allows the user to upload an image. After selecting an image, a modal opens with the uploaded image displayed inside.

You can view a demo of this functionality in action on this Fiddle Example:

Here is the corresponding code snippet:

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],                   
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
  $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
});
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>

<!-- Input for uploading images -->
<input type="file" id="input" name="image">

<!-- Modal for displaying uploaded image -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Image Upload</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div> <!-- .modal-header -->
      <div class="modal-body">
        <div class="container">
          <!-- Uploaded Image -->
          <img id="image" src="" alt="Picture">
        </div> <!-- .container -->
      </div> <!-- .modal-body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div> <!-- .modal-footer -->
    </div> <!-- .modal-content -->
  </div> <!-- .modal-dialog -->
</div> <!-- .modal -->

However, if I close the modal and try to upload the same image again, it does not open as expected because I am using the 'change' event listener.

I attempted to use the 'click' event instead:

$("#input").on("click", function(e) {});

Unfortunately, this resulted in errors and the modal not being shown:

Uncaught TypeError: Failed to execute 'createObjectURL' on 'URL': No function was found that matched the provided signature.

My next step will be to check the dimensions and size of the uploaded image.

So how do I modify my code to ensure that if I choose the same image again, it will still display properly in the modal?

Answer №1

To solve the issue, simply clear the value of your input attribute in the change event handler.

The problem lies in the fact that the change event of the input is not triggered when its val attribute remains unchanged. Make sure you differentiate between your img and input elements. Remember to release browser memory by calling revokeObjectURL and resetting the value of your input. If you don't reset the value, the change event won't be fired when opening the same file. Revoking the URL on the img element has no effect on the input element.

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],                   
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
  $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
  $(e.target.id).val(''); // <- ADD THIS
});
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>

<!-- Input to upload images -->
<input type="file" id="input" name="image">

<!-- Modal to show uploaded image on -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Image Upload</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div> <!-- .modal-header -->
      <div class="modal-body">
        <div class="container">
          <!-- Uploaded Image -->
          <img id="image" src="" alt="Picture">
        </div> <!-- .container -->
      </div> <!-- .modal-body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div> <!-- .modal-footer -->
    </div> <!-- .modal-content -->
  </div> <!-- .modal-dialog -->
</div> <!-- .modal -->

Answer №2

Clear input value when clicked

$("#input").on("change", function(e) {
  var _URL = window.URL || window.webkitURL,
      file = this.files[0],                   
      image = new Image();
  $('#image').attr('src',  _URL.createObjectURL(file));
  $(image).ready(function($) {
  $('#modal').modal('show');
  });
  window.URL.revokeObjectURL(image.src);
});
$("#input").on("click", function(e) {
var value= $('#input').val();
  if(value){
    $('#input').val('');
  }
});
<!-- jQuery -->
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<!-- Bootstrap JS -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.bundle.min.js"></script>

<!-- Input to upload images -->
<input type="file" id="input" name="image">

<!-- Modal to show uploaded image on -->
<div class="modal fade" id="modal" tabindex="-1" role="dialog" aria-labelledby="modalLabel" aria-hidden="true">
  <div class="modal-dialog" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="modalLabel">Image Upload</h5>
        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div> <!-- .modal-header -->
      <div class="modal-body">
        <div class="container">
          <!-- Uploaded Image -->
          <img id="image" src="" alt="Picture">
        </div> <!-- .container -->
      </div> <!-- .modal-body -->
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
      </div> <!-- .modal-footer -->
    </div> <!-- .modal-content -->
  </div> <!-- .modal-dialog -->
</div> <!-- .modal -->

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

Uncheck all boxes except for the required or disabled boxes in Angular

HTML: <mat-selection-list #selectedColumns [(ngModel)] ="selectedOptions"> <div class= "content-section"> <mat-expansion-panel> <mat-expansion-panel-header> ...

Is there a minimum height restriction for v-select in Vuetify.js?

Looking at the code snippet provided below, I am facing an issue while trying to decrease the height of a v-select element. It seems like there is a minimum limit set for the height, as reducing it beyond height = 40 doesn't have any effect. Is there ...

Concealing a child component when hovering over its parent element with styled-components

I have a react component structured like this - const MyComponent = () => ( <ContainerSection> <DeleteButtonContainer> <Button theme="plain" autoWidth onClick={() = ...

What is the process for executing JavaScript code that is stored as a string?

After making an AJAX call, I receive a random string (constructed dynamically on the server) that contains JavaScript code like: Plugins.add('test', function() { return { html: '<div>test</div&g ...

Unexpected issue with Ustream JSON API and jQuery

Recently, I attempted to execute the following jQuery code: var query = 'http://api.ustream.tv/json/channel/masaiblog/getValueOf/status?jsonp=?'; $.getJSON(query, function(data) { if (data['results'] == 'live') { ...

The schema encountered an error due to the absence of the save method

My current goal is to allow a logged in user to visit any user's URL and follow them. However, I'm encountering an issue: TypeError: Object { _id: 54bd6b90b7d4cc8c10b40cbd, name: 'Johnny', username: 'batman', __v: 0, ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

VueJS component fails to remain anchored at the bottom of the page while scrolling

I am currently using a <md-progress-bar> component in my VueJS application, and I am trying to make it stay fixed at the bottom of the screen when I scroll. I have attempted to use the styles position: fixed;, absolute, and relative, but none of them ...

Having trouble triggering a click event on Ant Design menu button using jest and enzyme

Troubleshooting the simulation of a click event on the Menu component using Antd v4.3.1 Component: import React from 'react' import PropTypes from 'prop-types' import { Menu } from 'antd' import { SMALL_ICONS, PATHS } fro ...

Increased wait time during initial execution

Currently facing an issue with delaying the first run of a function. I've developed a basic slideshow that is causing problems due to this delay in the initial run. My goal is to have the first run wait for 10 seconds and then maintain a 4-second del ...

What causes the input to be rendered as read-only when using the value attribute and as read-write when using the defaultValue attribute?

Within my shopping cart, the quantity of items added dynamically increases by +1 each time the same item is added. Additionally, users can manually adjust the quantity of an item within the cart to their preference. I encountered a dilemma with using the ...

React: When an array state is controlling my components, why aren't they re-rendering?

I am facing an issue with my app where the className of buttons is not updating correctly when clicked. It seems that only active buttons trigger a re-render, while non-active ones do not. This behavior is confusing to me. Here's the code snippet for ...

error": "message": "Property 'name' cannot be read because it is undefined

I've encountered an issue while creating a route to handle POST data. Despite testing it on postman, I have not been able to find a solution for the problem that many others seem to be facing as well. It seems like the 'name' field is not be ...

Utilizing various directives with distinct scopes for a single element

Is it possible for an element to have multiple directives with their own unique scopes? For example, let's consider a custom directive's child element with the controller's scope along with another directive (such as "ng-class"): <custo ...

Merge the chosen values from the drop-down menu into one string

Any suggestions would be greatly appreciated! I am currently developing an application using ASP.NET web forms that consists of a dropdown list and two list boxes. I want these elements to be cloned whenever a specific button is clicked. However, my issue ...

Guide on modifying CSS properties when hovering over the parent element

I am working with a table structure like this: <table> <tr><td class="momdad"><i class='glyphicon glyphicon-cog'></i> Hello </td><td> Mom </td></tr> <tr><td class="momdad">< ...

What is the process for establishing a reference to a property of an object in JavaScript?

Imagine you have an object structured like this: obj = {a:{aa:1}, b:2}; You decide to create a convenient variable (referred to as a pointer) named x that points to obj.a.aa with the following code: x = obj.a.aa; Next, your goal is to update the value ...

The presence of Vue refs is evident, though accessing refs[key] results in an

I am facing an issue with dynamically rendered checkboxes through a v-for loop. I have set the reference equal to a checkbox-specific id, but when I try to access this reference[id] in mounted(), it returns undefined. Here is the code snippet: let id = t ...

Issue with decompressing the identical data using zlib (Z_BUF_ERROR)

Below is the Python code snippet I am working with: import zlib raw = bytes.fromhex("789C34C9410AC2301005D0BBFC752289A88BB94A53CAD8061B48D3329D2A1A7277DDB87BF02A14548E9C0DF63FD60DE49DC104AA98238BDE23EB908A467972065DFCF9FAFB4185C708EAD0053C58E38BDF769 ...

Starting a Fresh Chapter Upon Successful Form Submission with PHP

https://i.sstatic.net/ZEHSL.png I am utilizing PHP to control form elements. If the elements are invalid, I display an error message below them. My issue arises when all form elements are valid, but the page does not redirect to the desired destination pa ...