简体   繁体   中英

jquery preview image not working

So I'm trying to implement a preview button so that when my users clicks on the upload button image they could have a preview but the thing is that it is not working, I wonder why ?? A brief description : I have a js function that creates new elements and append it to ap tag date. It is in this function that is going to create the preview image code

 // code for creating new elements function createElements(){ const userQuestions = document.querySelector('#userQuestions'); userQuestions.insertAdjacentHTML( 'beforeend', '<div class="uploader" onclick="$(\\'#filePhoto\\').click()"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" id="filePhoto" style="display:block;width:185px;" /></center><div class="grid-container">' ); } ///Code to preview image function handleImage(e) { var imageLoader = document.getElementById('filePhoto'); imageLoader.addEventListener('change', handleImage, false); var reader = new FileReader(); reader.onload = function (event) { $('.uploader').html( '<img width="300px" height="350px" src="'+event.target.result+'"/>' ); } reader.readAsDataURL(e.target.files[0]); } 
 .uploader {width:50%;height:35%;background:#f3f3f3;border:2px dashed #0091ea;} 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <button type="button" onclick="createElements()">add elements</button> </body> </html> 

If you run the snippet above you can see that the button is woeking but the preview is not showing. Could someone help me?

HTML:

<div class="row">
  <div class="col-xs-4">
    <div class="form-group">
      <label>Company Logo</label>
      <input type="file" class="form-control" value="" name="companyLogo" id="companyLogo" accept="image/*" />
    </div>
  </div>
  <div id="displayImage">
     <img id="imgData" src="#" alt="your image" height="150px" width="150px" />
  </div>
</div>

JavaScript:

$("#companyLogo").change(function(e) {
  if(e.target.value === "") {
    $("#displayImage").hide();
  } else {
    $("#displayImage").show();
  }
  readURL(this);
});

function readURL(input) {
  if (input.files && input.files[0]) {
    var reader = new FileReader();
    reader.onload = function(e) {
      $("#imgData").attr("src", e.target.result);
    }
    reader.readAsDataURL(input.files[0]);
  }
}

Short n simple

No need to create an element on click. Just add an image tag and set a default image like no image selected or something like that.

The following code will help you

<input type="file" name="myCutomfile" id="myCutomfile"/>


<img id="customTargetImg" src="default.jpg" width="400" height="250">

$("#myCutomfile").change(function() {    
    if (this.files && this.files[0]) {
        var reader = new FileReader();
        reader.onload = function (e) {
            $('#customTargetImg').attr('src', e.target.result);
        }
        reader.readAsDataURL(this.files[0]);
    }
});

Take advantage of jQuery -- particularly using

  1. event handlers
  2. delegated event handlers for dynamically-created elements
  3. tree traversal methods .

 $(function() { var userQuestions = $('#userQuestions'); // create onclick event handler for your button $('#addElements').click(function() { // IDs must be unique - since you can have an arbitrary number of filePhoto, use a class instead userQuestions.append( '<div class="uploader"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" class="filePhoto" /><div class="grid-container"></div>' ); }); // create delegated onclick event handler for your .uploader userQuestions.on('click', '.uploader', function() { // you only want to target the file input immediately after it $(this).next('[type=file]').click(); }); // create delegated onchange event handler for your .filePhoto userQuestions.on('change', '.filePhoto', function() { // find related uploader var uploader = $(this).prev('.uploader'); // check file was given if (this.files && this.files.length) { var reader = new FileReader(); reader.onload = function(event) { uploader.html('<img width="300px" height="350px" src="' + event.target.result + '"/>'); } reader.readAsDataURL(this.files[0]); } }); }); 
 .uploader { width: 50%; height: 35%; background: #f3f3f3; border: 2px dashed #0091ea; } .filePhoto { display: block; width: 185px; } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <!-- added ID attribute --> <button type="button" id="addElements">add elements</button> </body> </html> 

Edit

This answer is a non-jQuery solution based off your comment.

 // code for creating new elements function createElements() { // no need to document.querySelector if the selector is an ID const userQuestions = document.getElementById('userQuestions'); // you want to use onclick/onchange attributes here as they are dynamically created userQuestions.insertAdjacentHTML( 'beforeend', '<div class="uploader" onclick="selectFile(this)"><p id="bg-text">No image</p></div><input type="file" name="userprofile_picture" onchange="handleImage(this)" />' ); } // trigger click on file input that follows the uploader function selectFile(uploader) { uploader.nextSibling.click(); } ///Code to preview image function handleImage(input) { if (input.files.length) { var reader = new FileReader(); reader.onload = function(e) { input.previousSibling.innerHTML = '<img width="300px" height="350px" src="' + e.target.result + '"/>'; } reader.readAsDataURL(input.files[0]); } } 
 .uploader { width: 50%; height: 35%; background: #f3f3f3; border: 2px dashed #0091ea; } .filePhoto { display: block; width: 185px; } 
 <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> </head> <body> <div id="userQuestions"></div> <button type="button" onclick="createElements()">add elements</button> </body> </html> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM