Incorporate a custom file input field and utilize jQuery to switch out the input type with a chosen image

.image-upload > input
{
    display: none;
}
.upload-icon{
width: 100px;
height: 97px;
border: 2px solid #5642BE;
border-style: dotted;
border-radius: 18px;
}
.upload-icon img{
width: 60px;
height: 60px;
margin:19px;
cursor: pointer;
}
<form>
      <div class="image-upload">
         <label for="file-input">
           <div class="upload-icon">
            <img src="https://image.flaticon.com/icons/png/128/61/61112.png">
            </div>
          </label>
       <input id="file-input" type="file"/>
      </div>
 </form>

I wish to allow only image uploads using an input of type file. When an image is selected for upload, the upload image icon should be replaced with the selected image (similar to the screenshot below). I haven't written any script yet. What script should I use? https://i.sstatic.net/aAmZg.png

Answer №1

You may want to consider using jQuery to achieve this functionality. Below is an example that demonstrates how it can be done.

Here is the code snippet for creating a preview:

function displayImage(input) {
  var identifier = $(input).attr("id");

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

    reader.onload = function(e) {
      $('label[for="' + identifier + '"] .upload-icon').css("border", "none");
      $('label[for="' + identifier + '"] .icon').hide();
      $('label[for="' + identifier + '"] .prev').attr('src', e.target.result).show();
    }

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

$("input[id^='file-input']").change(function() {
  displayImage(this);
});

I have made it more dynamic so you can use the input field multiple times, similar to your image example.

Hopefully, this solution proves to be helpful for you.

function displayImage(input) {
  var identifier = $(input).attr("id");

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

    reader.onload = function(e) {
      $('label[for="' + identifier + '"] .upload-icon').css("border", "none");
      $('label[for="' + identifier + '"] .icon').hide();
      $('label[for="' + identifier + '"] .prev').attr('src', e.target.result).show();
    }

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

$("input[id^='file-input']").change(function() {
  displayImage(this);
});
.image-upload>input {
  display: none;
}

.upload-icon {
  width: 100px;
  height: 97px;
  border: 2px solid #5642BE;
  border-style: dotted;
  border-radius: 18px;
  float: left;
}

.upload-icon .icon {
  width: 60px;
  height: 60px;
  margin: 19px;
  cursor: pointer;
}

.prev {
  display: none;
  width: 95px;
  height: 92px;
  margin: 2px;
  border-radius: 15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="image-upload">
    <label for="file-input">
           <div class="upload-icon">
            <img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            <img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            </div>
          </label>
    <input id="file-input" type="file" />
  </div>
  <div class="image-upload">
    <label for="file-input2">
           <div class="upload-icon">
            <img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            <img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            </div>
          </label>
    <input id="file-input2" type="file" />
  </div>
  <div class="image-upload">
    <label for="file-input3">
           <div class="upload-icon">
            <img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            <img class="prev" src="https://image.flaticon.com/icons/png/128/61/61112.png">
            </div>
          </label>
    <input id="file-input3" type="file" />
  </div>
</form>

Answer №2

Using just one line of code, you can easily achieve this. By utilizing URL.createObjectURL(), you can create the desired functionality. Check out the snippet below for a working example:

$('#file-input').change( function(event) {
    $("img.icon").attr('src',URL.createObjectURL(event.target.files[0]));
    $("img.icon").parents('.upload-icon').addClass('has-img');
});
.image-upload > input
{
    display: none;
}
.upload-icon{
  width: 100px;
  height: 97px;
  border: 2px solid #5642BE;
  border-style: dotted;
  border-radius: 18px;
}
.upload-icon img{
  width: 60px;
  height: 60px;
  margin:19px;
  cursor: pointer;
}
.upload-icon.has-img {
    width: 100px;
    height: 97px;
    border: none;
}
.upload-icon.has-img img {
    width: 100%;
    height: auto;
    border-radius: 18px;
    margin:0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
  <div class="image-upload">
 <label for="file-input">
   <div class="upload-icon">
<img class="icon" src="https://image.flaticon.com/icons/png/128/61/61112.png">
</div>
  </label>
   <input id="file-input" type="file"/>
  </div>
 </form>

Answer №3

It seems like you are looking to display a preview of the image you have selected.

        $("#file-input").change(function () {
            readURL(this, 'sampleImageId');
            $('.upload-icon').css('border-style','none');
        });
        
        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]);

        }
      }
.image-upload > input
    {
        display: none;
    }
    .upload-icon{
    width: 100px;
    height: 97px;
    border: 2px solid #5642BE;
    border-style: dotted;
    border-radius: 18px;
    }
    .upload-icon img{
    width: 90px;
    height: 87px;
    margin:5px;
    cursor: pointer;
    }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<form>
          <div class="image-upload">
             <label for="file-input">
               <div class="upload-icon">
                <img id="sampleImageId" src="https://image.flaticon.com/icons/png/128/61/61112.png">
                </div>
              </label>
           <input id="file-input" type="file"/>
          </div>
     </form>

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

unable to retrieve the JSON data from the provided link

I'm having trouble retrieving JSON data from a specific link using my script. If there are any mistakes in my code, please let me know. Thank you in advance for your help. <script type="text/javascript"> function getSomething() ...

Obtain the final tr element that has an id starting with Row_

Is there a way to use jQuery to retrieve the highest id for all tr elements within a table? Consider the following table: <table id="productsTable" style="width:100%;"> <thead> <tr> <td colspan="4"></td& ...

Guide on removing the <hr/> tag only from the final list item (li) in an Angular

This is my Angular view <li class= "riskmanagementlink" ng-repeat="link in links"> <h3> {{link.Description}} </h3> <a> {{link.Title}} </a> <hr/> </li> I need assistance with removing the hr tag for the l ...

The functionality of angular ng-show/ng-hide is not functioning properly when used in conjunction with ng-bind-html

I am having an issue with setting ng-show or ng-hide for my elements in an HTML string and passing it to the view using ng-bind-html. Unfortunately, the ng-show/ng-hide functionality is not working as expected and my element is always visible. Below is my ...

The phenomenon of jQuery AJAX converting the escape character from %20 to + has been observed

I am encountering an issue with my jQuery AJAX function which is supposed to save an image path to the database. Below is an example parameter: var data = {}; data['url'] = "Path%20to%20URL"; Normally, if there is a space or %20, it sh ...

Hide the unattractive focus border in Bootstrap-Select

I've been trying to remove a black border surrounding my selectpicker list box: https://i.sstatic.net/V2rNq.png Even without focus, the border persists: https://i.sstatic.net/ncoDM.png Despite using outline: none; in my CSS, the unwanted border re ...

Use of number type input on mobile devices in HTML

My goal is to display the up/down arrows alongside an input element with type="number" in Chrome on Android. I've adjusted the CSS to set opacity=1, but unfortunately, they are not appearing. On desktop, however, they show up without any iss ...

How can we use an SQL query to identify shared data that meets multiple conditions within a single table?

I am in possession of a list of country codes, each with its own account holder counts. My goal is to retrieve the account numbers along with the corresponding country codes for countries that are present in multiple locations. For example: https://i.sst ...

Is the integer node reaching its limit?

Could someone guide me through this? $node -v v0.10.10 $ node > (10000000)>>1 5000000 > (100000000)>>1 50000000 > (1000000000)>>1 500000000 > (10000000000)>>1 705032704 Is it expected that 2^53 is the maximum integer ...

How can I display a Bootstrap modal in Ember.js after rendering it in an outlet?

I'm facing a challenge in my Ember.js application where I need to trigger the opening of a Bootstrap modal from my ApplicationRoute upon calling the openModal action. This is what my ApplicationRoute looks like: module.exports = Em.Route.extend({ ...

Troubleshooting problem with media queries and max-width

Is there a way to remove an HTML element using the display:none property when the screen width is below 500px? @media (max-width:500px) { button { display:none}; } <button>Test</button> The issue at hand is that the button disappe ...

Running the Spring Tool Suite IDE on a Windows system: A step-by-step guide

Hey there, I need some assistance with Spring Tool Suit IDE Running. I recently installed it on my system and a shortcut was created on my desktop. However, when I click on it, I encounter the following exception! Java was started but returned exit code = ...

The webpage is jolting every time it's reloaded

I'm facing a frustrating issue on my website. Every time I refresh the page, it jerks and the text seems to compress and then return to normal. Even after removing most of my code, the problem persists and I can't figure out what's causing i ...

What could be the reason for the model not being updated within this recurring Angular directive?

I've been pondering this all day. Why aren't the names updating when I enter text in the fields? Everything seems correct. What could be going awry? To sum it up: I am attempting to create a recursive directive that, when it encounters an objec ...

Is there a way for me to specifically show just the initial image contained in the images[] array within the json data?

{"status": true, "data": {"basic": {"dob": "2018-02-02", "gender": "male", "contact": {"address": null}, "is_new": false, "is_email_verified": false, "is_phone_verified": false}, "listings": [{"pid": 109, "category": {"name": "Education"}, "location": {"l ...

Using Javascript to perform redirects within a Rails application

Currently working on a Facebook application using Rails. There are certain pages that require users to be logged in, otherwise they will be directed to a "login" page. I am unable to use redirect_to for this purpose as the redirection must be done through ...

Attempting to convert a Raw image file and upload it onto the server

I am currently attempting to upload an image to my server using PHP. I have two files for this task - index.php and myscript.php. Index.php <div id="results">Your captured image will appear here...</div> <h1>Mugshot Test Page& ...

Can a link be generated that swaps out the original URL redirect for the following visitor upon clicking?

Can the program be fed with a list of links to automatically redirect to the next URL once clicked? In this setup, each visitor would only see one link and not have access to any other URLs in the chain. Is there a way to make this happen? Any suggestion ...

CSS delays affecting the loading of the page's display

I am currently working on a WordPress website and I have noticed that one of the CSS files takes approximately 10 seconds to load, causing a significant delay in displaying the page. I am looking for ways to speed up this loading process. As part of my ef ...

React - Trouble rendering JSON file

I am working on a row of react-icons. Once clicked, the icons should display content from a static .JSON file. I am trying to achieve the following functionalities: Change color when clicked Switch between the static .JSON content when clicked. I at ...