skip to Main Content

I want to use jquery function multiple times with different ID’s to upload different images. For example if I use input field with id=myImg1 for upload an image, it should’t upload this image for input field with id=myImg=2, but it does so. I want to try something like for loop, but don’t understand how to do it.

I’ve tried this code:

$(function() {
    $(":file").change(function() {
      if (this.files && this.files[0]) {
        for (var i = 0; i < this.files.length; i++) {
          var reader = new FileReader();
          reader.onload = imageIsLoaded;
          reader.readAsDataURL(this.files[i]);
        }
      }
    });
  });
  
  function imageIsLoaded(e) {
    $('div[id^=myImg]').append('<img src=' + e.target.result + '>');
  };
<input type="file" multiple/>
<div id="myImg1"></div>
          
<p>Геоморфология</p> 
<input type="text" placeholder="" name="place" class="input"/><br>
<input type="file" multiple/> 
<div id="myImg2"></div>    

This results in
this

3

Answers


  1. It’s because you should append into the needed div, instead of appending into all the div‘s

    In my example I am passing the extra data-id attr to the input and based on that I am identifying to which div should I append the current image.

    $(function() {
      $(":file").change(function() {
        if (this.files && this.files[0]) {
          for (var i = 0; i < this.files.length; i++) {
            var reader = new FileReader();
            var imageDivID = $(this).data("id")
            reader.onload = function(e) {
              imageIsLoaded(e, imageDivID);
            }
            reader.readAsDataURL(this.files[i]);
          }
        }
      });
    });
      
    function imageIsLoaded(e, imageDivID) {
      $("div#"+imageDivID).append('<img src=' + e.target.result + '>');
    };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <input type="file" data-id="myImg1" multiple/>
    <div id="myImg1"></div>
              
    <p>Геоморфология</p> 
    <input type="text" placeholder="" name="place" class="input"/><br>
    <input type="file" data-id="myImg2" multiple/> 
    <div id="myImg2"></div>
    Login or Signup to reply.
  2. You can simplify your code…

    by replacing FileReader with URL.createObjectURL. This allows you to append the images in one step:

    element.append('<img src="' + URL.createObjectURL(file) + '">')
    

    And adding the accept attribute to the file inputs will make it easier for users to select only images.

    <input type="file" accept="image/*">
    

    Your problem is solved with jQuery.next which appends the images to the next matching id:

    $(this).next("[id^=myImg]").append()
    

    Combining these changes we get this snippet:

    $(":file").change(function(e) {
    
      [...this.files].forEach(file => {
    
        $(this).next('[id^=myImg]').append('<img src="' + URL.createObjectURL(file) + '">')
        
      })
      
    })
    /* image display */
    
    [id^=myImg] {
      display: flex;
      flex-direction: row;
      flex-wrap: wrap;
      justify-content: start;
      gap: 1rem;
      border: thin solid gray;
      border-radius: 0.5rem;
      padding: 0.5rem;
    }
    
    [id^=myImg] img {
      max-width: 150px;
      max-height: 150px;
     }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    
    <input name="files" type="file" multiple accept="image/*">
    <div id="myImg1"></div>
    
    <p>Геоморфология</p>
    <input type="text" name="place"><br>
    <input name="files" type="file" multiple accept="image/*">
    <div id="myImg2"></div>
    Login or Signup to reply.
  3. Since the DIV is always the next element after the file input, use $(this).next() to select it, rather than selecting by ID.

    $(function() {
      $(":file").change(function() {
        if (this.files && this.files[0]) {
          $(this).next().empty();
          for (var i = 0; i < this.files.length; i++) {
            var reader = new FileReader();
            reader.onload = (e) => imageIsLoaded(e, $(this).next());
            reader.readAsDataURL(this.files[i]);
          }
        }
      });
    });
    
    function imageIsLoaded(e, div) {
      div.append('<img src=' + e.target.result + '>');
    };
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <input type="file" multiple/>
    <div id="myImg1"></div>
    
    <p>Геоморфология</p>
    <input type="text" placeholder="" name="place" class="input"/><br>
    <input type="file" multiple/>
    <div id="myImg2"></div>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search